home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 March: Reference Library / Dev.CD Mar OO RLDisk 1.toast / pc / what's new / development kits / hardware / mac os usb ddk 1.4f3 / examples / printerclassdriver / printerclassdriver.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-01-20  |  125.7 KB  |  3,827 lines

  1. /*
  2.     File:        PrinterClassDriver.c
  3.  
  4.     Contains:    MacOS USB printer class driver
  5.                 [ref. IEEE Std 1284-1994]
  6.  
  7.     Version:    xxx put version here xxx
  8.  
  9.  
  10.  
  11.     Copyright:    1998 by Apple Computer, Inc., all rights reserved.
  12.  
  13. */
  14.  
  15.  
  16. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  17.     includes
  18.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  19. #include <Gestalt.h>
  20. #include <Devices.h>
  21. #include <DriverServices.h>
  22. #include <Interrupts.h>
  23. #include <LowMem.h>
  24. #include <Folders.h>
  25. #include <String.h>
  26. #include <stdio.h>
  27. #include <ctype.h>
  28. #include <USB.h>
  29.  
  30. #ifndef __CODEFRAGMENTS__
  31. #include <codefragments.h>
  32. #endif
  33.  
  34. #include "PrinterClassDriver.h"
  35. #include "TradDriverLoaderLib.h"
  36.  
  37. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  38.     constants
  39.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  40. #define MAX_SUFFIX                    127                    // maximum copies we'll enter in unit table
  41. #define kUSBParallelDrvrRsrcID        12
  42. #define kMinDrvrUnitNumber            48                    // minimum unit table entry which we'll install
  43. #define kUSS720MillisecondDelay        3*1000                // poll every three seconds
  44. #define kUSS720StatusMSDelay        100                    // poll ten times per second
  45. #define MAX_USB_TRANSFER_SIZE        TRANSFER_SIZE        // zero acts as manifest for conditional compilation
  46.  
  47. #define kUSBAttributeBulk            0x02
  48. #define kUSBInputEndpointMask        0x80
  49.  
  50. #define kDebugStatusLevel            5
  51. #define kNormalStatusLevel            4
  52.  
  53.  
  54. enum
  55. {
  56.     kUSBv12    =    0x01200000
  57. };
  58.  
  59. enum
  60. {
  61.     kCString = 0,                // StateStr, USBStatusStr selector
  62.     kPString,                    // StateStr, USBStatusStr selector
  63.     kDrvrFirstDigit = 5            // length_byte + ".USB" = 5
  64. };
  65. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  66.     manifest constants
  67. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  68. //
  69. //    DEBUGGING                        extra debugging information to USB Expert Log
  70. //    DOUBLE_BUFFER                    use a page aligned buffer in system heap to double buffer app i/o
  71. //    LOG                                echo all the write data to a log file in the system folder
  72. // LOCK_MEMORY                        LockMemory on the i/o buffer before write and unlock on write completion
  73. // VIRTUAL_MEMORY_CHECK                check the physical addresses of the buffer we pass for write requests
  74. // MACSBUG_ON_READ                    break into MacsBug before each read request
  75. //    MACSBUG_ON_READ_COMPLETE        break into MacsBug at each read completion routine
  76. //    MACSBUG_ON_WRITE                break into MacsBug on each write request
  77. // MACSBUG_ON_WRITE_COMPLETE        break into MacsBug at each write completion routine
  78. //
  79. #define DEBUGGING                        0    /* DEBUGGING */
  80. #define DOUBLE_BUFFER                    1    /* DOUBLE_BUFFER */
  81. #define LOG                                0    /* LOG */
  82. #define LOCK_MEMORY                        1    /* LOCK_MEMORY */
  83. #define MACSBUG_ON_READ                    0    /* MACSBUG_ON_READ */
  84. #define MACSBUG_ON_READ_COMPLETE        0    /* MACSBUG_ON_READ_COMPLETE */ 
  85. #define MACSBUG_ON_WRITE                0    /* MACSBUG_ON_WRITE */
  86. #define MACSBUG_ON_WRITE_COMPLETE        0    /* MACSBUG_ON_WRITE_COMPLETE */ 
  87. #define VIRTUAL_MEMORY_CHECK            0    /* VIRTUAL_MEMORY_CHECK requires LOCK_MEMORY */
  88.  
  89. #if LOG
  90. #define LOGGING(x)    x
  91. #include <stdio.h>
  92. #else
  93. #define LOGGING(x)
  94. #endif
  95.  
  96. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97.     globals
  98.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  99. static struct usbPrinterPBStruct    printerClassRecord;
  100. static FSSpec                            printerClassDriverFileSpec;
  101. LOGGING( static FILE                    *logfile );
  102.  
  103. SInt16    openRef = 0;        // used to only suspend on last close
  104.  
  105. volatile enum{
  106.     kUSBPrintSuspended,
  107.     kUSBPrintResumed
  108.     }wantToBe = kUSBPrintResumed, currentlyAre = kUSBPrintResumed;
  109.  
  110. // These for resuming reads, writes and control calls which were delayed due to resume
  111.  
  112. IOParamPtr Wpb; DCtlPtr Wctl; struct usbPrinterPBStruct *WpPrinterPB;
  113. IOParamPtr Rpb; DCtlPtr Rctl; struct usbPrinterPBStruct *RpPrinterPB;
  114. IOParamPtr Cpb; DCtlPtr Cctl; struct usbPrinterPBStruct *CpPrinterPB;
  115.  
  116. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  117.     prototypes
  118.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  119.  
  120. static void    PrinterDeviceCompletionProc(USBPB *pb);
  121. static void SetNullUSBParamBlock( USBDeviceRef dev, USBPB *pb );
  122. static void    SoftReset( USBPB *usbprint, short interfaceNum );
  123. static void    ClearEndpointHalt( USBPB *usbprint);
  124. static void    CapabilityRequest( USBPB *pb, Ptr p, long length, short config, short interfaceNum, short alternateSetting );
  125. static void    CentronicsStatus( USBPB *usbprint, Ptr p, short interfaceNum );
  126. static void CompletionProc(USBPB *pb);
  127.  
  128. void            PrinterDeviceInitiateTransaction(USBPB *pb);
  129.  
  130. OSErr            CFMInitialization( CFragInitBlock *initBlock );
  131.  
  132. Boolean    gUSBVersionNeedsBulkFixPresent;
  133.  
  134. void        CheckUSBVersion(void);
  135. OSStatus     SecondaryUSBBulkRead(void *pb, void *result);
  136. OSStatus     SecondaryUSBBulkWrite(void *pb, void *result);
  137. OSStatus     SafeUSBBulkRead(USBPB *pb);
  138. OSStatus     SafeUSBBulkWrite(USBPB *pb);
  139.  
  140. void    CheckUSBVersion(void)
  141. {
  142. OSStatus    err;
  143. UInt32        usbVersion;
  144.  
  145.     err = Gestalt('usbv', (long*)&usbVersion);
  146.     if (err == noErr)
  147.         gUSBVersionNeedsBulkFixPresent = (usbVersion < kUSBv12);
  148. }
  149.  
  150. OSStatus SecondaryUSBBulkRead(void *pb, void *result)
  151. {
  152.     *(OSStatus*)result = USBBulkRead((USBPB*)pb);
  153.     return noErr;
  154. }
  155.  
  156. OSStatus SecondaryUSBBulkWrite(void *pb, void *result)
  157. {
  158.     *(OSStatus*)result = USBBulkWrite((USBPB*)pb);
  159.     return noErr;
  160. }
  161.  
  162. OSStatus SafeUSBBulkRead(USBPB *pb)
  163. {
  164.     OSStatus    result;
  165.  
  166.     pb->usbFlags = 0;    // BT we may have set the address request flag
  167.     if (gUSBVersionNeedsBulkFixPresent)
  168.     {
  169.         // Use CallSecondaryInterruptHandler2 to call USBBulkRead if
  170.         // less than USB v1.2 present
  171.         CallSecondaryInterruptHandler2(SecondaryUSBBulkRead, nil, pb, &result);
  172.     }
  173.     else
  174.         result = USBBulkRead(pb);
  175.         
  176.     return result;
  177. }
  178.  
  179. OSStatus SafeUSBBulkWrite(USBPB *pb)
  180. {
  181.     OSStatus    result;
  182.  
  183.     pb->usbFlags = 0;    // BT we may have set the address request flag
  184.     if (gUSBVersionNeedsBulkFixPresent)
  185.     {
  186.         // Use CallSecondaryInterruptHandler2 to call USBBulkWrite if
  187.         // less than USB v1.2 present
  188.         CallSecondaryInterruptHandler2(SecondaryUSBBulkWrite, nil, pb, &result);
  189.     }
  190.     else
  191.         result = USBBulkWrite(pb);
  192.         
  193.     return result;
  194. }
  195.  
  196.  
  197.  
  198.  
  199. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  200.     Name:        HexString8
  201.  
  202.     Input Parameters:    
  203.         v                unsigned long value
  204.         
  205.     Output Parameters:
  206.         p                8 bytes: hex string representing value
  207.         
  208.     Description:
  209.  
  210.  
  211.  
  212. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  213. static void
  214. HexString8( unsigned long v, unsigned char *p )
  215. {
  216.     short    shift;
  217.     
  218.     for ( shift = 32-4; shift >= 0; shift -= 4 )
  219.     {
  220.         char c = (v >> shift) & 0x0F;
  221.         *p++ = c + (c > 9? ('A'-10): '0');
  222.     }
  223. }
  224.  
  225. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  226.     Name:        hexstr
  227.  
  228.     Input Parameters:    
  229.         count                number of bytes
  230.         p                    pointer to bytes
  231.         
  232.     Output Parameters:
  233.         q                    hex dump of data
  234.         
  235.     Description:
  236.  
  237.  
  238.  
  239. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  240. void hexstr( long count, char *p, char *q )
  241. {
  242.     char *s = p;
  243.     long i = count;
  244.     for ( ; count > 0; --count, ++p )
  245.     {
  246.         UInt8 hi, lo;
  247.         hi = (*p >> 4)& 0x0F;
  248.         lo = *p & 0x0F;
  249.         *q++ = '0';
  250.         *q++ = 'x';
  251.         *q++ = hi + (hi > 9? 'A' - 10: '0');
  252.         *q++ = lo + (lo > 9? 'A' - 10: '0');
  253.         *q++ = ' ';
  254.     }
  255.     for ( ; i > 0; --i, ++s )
  256.         *q++ = *s < ' ' || *s > 0x7E? '.': *s;
  257. }
  258.  
  259. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  260.     Name:        ForceUpperStr
  261.  
  262.     Input Parameters:    
  263.         s                    pointer to a null terminated string
  264.         
  265.     Output Parameters:
  266.         s                    string modified by using toupper() on each character.
  267.         
  268.     Description:
  269.  
  270.  
  271.  
  272.  
  273. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  274. void 
  275. ForceUpperStr(char *s)
  276. {
  277.     while(*s){
  278.         *s = toupper(*s);
  279.         s++;
  280.     }
  281. }
  282.     
  283. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  284.     Name:        MakeNameRegistrySafeStr
  285.  
  286.     Input Parameters:    
  287.         s                    pointer to a null terminated string
  288.         
  289.     Output Parameters:
  290.         s                    string modified by replacing / with - on each character.
  291.         
  292.     Description:
  293.  
  294.  
  295.  
  296. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  297. void 
  298. MakeNameRegistrySafeStr(char *s)
  299. {
  300.     while (*s)
  301.     {
  302.         if (*s == '/') 
  303.             *s = '-';
  304.         s++;
  305.     }
  306. }
  307.  
  308.  
  309.  
  310. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  311.     Name:        USBStatusStr
  312.  
  313.     Input Parameters:    
  314.         usbStatus            usb error code
  315.         kind                    kPString or kCString
  316.         
  317.     Output Parameters:
  318.         unsigned char *    description of error (c-string or p-string)
  319.  
  320.     Description:
  321.         a simple mapping of errors to human-readable form
  322.  
  323.  
  324.  
  325.  
  326.  
  327. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  328. static unsigned char *
  329. USBStatusStr( OSStatus usbStatus, short kind )
  330. {
  331.     unsigned char *p;
  332.  
  333.     switch ( usbStatus )
  334.     {
  335.         case    kUSBInternalErr:                    p = kPStrPrinterDriverName"Internal error"; break;
  336.         case    kUSBUnknownDeviceErr:                p = kPStrPrinterDriverName"Unknown device"; break;
  337.         case    kUSBUnknownPipeErr:                 p = kPStrPrinterDriverName"Unknown pipe"; break;
  338.         case    kUSBTooManyPipesErr:                p = kPStrPrinterDriverName"Too many pipes"; break;
  339.         case    kUSBIncorrectTypeErr:                p = kPStrPrinterDriverName"Incorrect type"; break;
  340.         case    kUSBRqErr:                            p = kPStrPrinterDriverName"Request error"; break;
  341.         case    kUSBUnknownRequestErr:                p = kPStrPrinterDriverName"Unknown request"; break;
  342.         case    kUSBTooManyTransactionsErr:            p = kPStrPrinterDriverName"Too many transactions"; break;
  343.         case    kUSBAlreadyOpenErr:                    p = kPStrPrinterDriverName"Already open"; break;
  344.         case    kUSBNoDeviceErr:                    p = kPStrPrinterDriverName"No device"; break;
  345.         case    kUSBDeviceErr:                        p = kPStrPrinterDriverName"Device error"; break;
  346.         case    kUSBOutOfMemoryErr:                    p = kPStrPrinterDriverName"Out of memory"; break;
  347.         case    kUSBNotFound:                        p = kPStrPrinterDriverName"Not found"; break;
  348.         case    kUSBPBVersionError:                    p = kPStrPrinterDriverName"Wrong pbVersion"; break;
  349.         case    kUSBPBLengthError:                    p = kPStrPrinterDriverName"pbLength too small"; break;
  350.         case    kUSBCompletionError:                p = kPStrPrinterDriverName"Missing completion routine"; break;
  351.         case    kUSBFlagsError:                        p = kPStrPrinterDriverName"Unused flags not zeroed"; break;
  352.         case    kUSBAbortedError:                    p = kPStrPrinterDriverName"Pipe aborted"; break;
  353.         case    kUSBNoBandwidthError:                p = kPStrPrinterDriverName"No bandwidth available"; break;
  354.         case    kUSBPipeIdleError:                    p = kPStrPrinterDriverName"Pipe is idle"; break;
  355.         case    kUSBPipeStalledError:                p = kPStrPrinterDriverName"Pipe is stalled"; break;
  356.         case    kUSBUnknownInterfaceErr:            p = kPStrPrinterDriverName"Unknown interfaceRef"; break;
  357.         case    kUSBDeviceBusy:                        p = kPStrPrinterDriverName"Device is busy"; break;
  358.         case    kUSBDevicePowerProblem:                p = kPStrPrinterDriverName"Device power problem"; break;
  359.         case    kUSBInvalidBuffer:                    p = kPStrPrinterDriverName"Bad buffer (nil?)"; break;
  360.         case    kUSBDeviceSuspended:                p = kPStrPrinterDriverName"Device is suspended"; break;
  361.         case    kUSBDeviceNotSuspended:                p = kPStrPrinterDriverName"Device is not suspended"; break;
  362.         case    kUSBDeviceDisconnected:                p = kPStrPrinterDriverName"Disconnected during suspend/reset"; break;
  363.         case    kUSBTimedOut:                        p = kPStrPrinterDriverName"Transaction timed out"; break;
  364.  
  365.         case    kUSBLinkErr:                        p = kPStrPrinterDriverName"Link Err"; break;
  366.         case    kUSBCRCErr:                            p = kPStrPrinterDriverName"Comms/Device err, bad CRC";  break;        
  367.         case    kUSBBitstufErr:                        p = kPStrPrinterDriverName"Comms/Device err, bitstuffing"; break;        
  368.         case    kUSBDataToggleErr:                    p = kPStrPrinterDriverName"Comms/Device err, Bad data toggle"; break;        
  369.         case    kUSBEndpointStallErr:                p = kPStrPrinterDriverName"Device didn't understand"; break;        
  370.         case    kUSBNotRespondingErr:                p = kPStrPrinterDriverName"No device, device hung"; break;        
  371.         case    kUSBPIDCheckErr:                    p = kPStrPrinterDriverName"Comms/Device err, PID CRC error"; break;        
  372.         case    kUSBWrongPIDErr:                    p = kPStrPrinterDriverName"Comms/Device err, Bad or wrong PID"; break;        
  373.         case    kUSBOverRunErr:                        p = kPStrPrinterDriverName"Packet too large or more data than buffer"; break;        
  374.         case    kUSBUnderRunErr:                    p = kPStrPrinterDriverName"Less data than buffer"; break;        
  375.         case    kUSBRes1Err:                        p = kPStrPrinterDriverName"kUSBRes1Err"; break;        
  376.         case    kUSBRes2Err:                        p = kPStrPrinterDriverName"kUSBRes1Err"; break;        
  377.         case    kUSBBufOvrRunErr:                    p = kPStrPrinterDriverName"Buffer over run error"; break;        
  378.         case    kUSBBufUnderRunErr:                    p = kPStrPrinterDriverName"Buffer under run error"; break;        
  379.         case    kUSBNotSent1Err:                    p = kPStrPrinterDriverName"Transaction not sent1"; break;        
  380.         case    kUSBNotSent2Err:                    p = kPStrPrinterDriverName"Transaction not sent2"; break;    
  381.         default:
  382.             p = kPStrPrinterDriverName"Unknown error nnnnnnnn";
  383.             HexString8( usbStatus, p + *p - 8 + 1 );
  384.             break;
  385.     }
  386.     
  387.     return kind == kPString? p: p + 1;
  388. }
  389.  
  390. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  391.     Name:        StateStr
  392.  
  393.     Input Parameters:    
  394.         usbRefCon            usb error code
  395.         kind                    kPString or kCString
  396.         
  397.     Output Parameters:
  398.         unsigned char *    description of state (c-string or p-string)
  399.  
  400.     Description:
  401.         a simple mapping of states to human-readable form
  402.  
  403.  
  404.  
  405.  
  406.  
  407. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  408. static unsigned char *
  409. StateStr( OSStatus refCon, short kind )
  410. {
  411.     unsigned char *p;
  412.  
  413.     refCon &= ~(kTransactionPending | kRetryTransaction | kReturnFromDriver);
  414.     switch ( refCon )
  415.     {
  416.         case kUndefined:                            p = kPStrPrinterDriverName"kUndefined"; break;
  417.         case kNilCompletion:                        p = kPStrPrinterDriverName"kNilCompletion"; break;
  418.  
  419.         case kFindInterface_bidirectional:            p = kPStrPrinterDriverName"kFindInterface_bidirectional"; break;
  420.         case kFindInterface_unidirectional:            p = kPStrPrinterDriverName"kFindInterface_unidirectional"; break;
  421.         case kOpenDevice:                            p = kPStrPrinterDriverName"kOpenDevice"; break;
  422.         case kNewInterfaceRef:                        p = kPStrPrinterDriverName"kNewInterfaceRef"; break;
  423.  
  424.         case kSetInterface:                            p = kPStrPrinterDriverName"kSetInterface"; break;
  425.         case kConfigureInterface:                    p = kPStrPrinterDriverName"kConfigureInterface"; break;
  426.         case kGetCapabilityString:                    p = kPStrPrinterDriverName"kGetCapabilityString"; break;
  427.         case kDelayGetCapability:                    p = kPStrPrinterDriverName"kDelayGetCapability"; break;
  428.  
  429.         case kAllocateCapabilityMem:                p = kPStrPrinterDriverName"kAllocateCapabilityMem"; break;
  430.         case kGetFullCapabilityString:                p = kPStrPrinterDriverName"kGetFullCapabilityString"; break;
  431.         case kGetInterface:                            p = kPStrPrinterDriverName"kGetInterface"; break;
  432.         case kFindBulkOutPipe:                        p = kPStrPrinterDriverName"kFindBulkOutPipe"; break;
  433.  
  434.         case kFindBulkInPipe:                        p = kPStrPrinterDriverName"kFindBulkInPipe"; break;
  435.         case kTaskTimeRequired:                        p = kPStrPrinterDriverName"kTaskTimeRequired"; break;
  436.  
  437.         case kGetCentronicsStatus:                    p = kPStrPrinterDriverName"kGetCentronicsStatus"; break;
  438.         case kDelayGetCentronicsStatus:                p = kPStrPrinterDriverName"kDelayGetCentronicsStatus"; break;
  439.  
  440.         case kDeallocateCapbilityString:            p = kPStrPrinterDriverName"kDeallocateCapbilityString"; break;
  441.         default:
  442.             p = kPStrPrinterDriverName"Unknown state nnnnnnnn";
  443.             HexString8( refCon, p + *p - 8 + 1 );
  444.             break;
  445.     }
  446.     return kind == kPString? p: p + 1;    
  447. }
  448.  
  449. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  450.     Name:        HiHex
  451.  
  452.     Input Parameters:    
  453.         v                        only low byte used
  454.         
  455.     Output Parameters:
  456.         <function result>    high nibble represented as ASCII char
  457.         
  458.     Description:
  459.  
  460.  
  461.  
  462. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  463. static unsigned char
  464. HiHex( unsigned char v )
  465. {
  466.     unsigned char    hinibble = (v >> 4) & 0x0f;
  467.     return hinibble + ((hinibble > 9)? ('A'-10): '0');
  468. }
  469.  
  470. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  471.     Name:        LoHex
  472.  
  473.     Input Parameters:    
  474.         v                        only low byte used
  475.         
  476.     Output Parameters:
  477.         <function result>    low nibble represented as ASCII char
  478.         
  479.     Description:
  480.  
  481.  
  482.  
  483. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  484. static unsigned char
  485. LoHex( unsigned char v )
  486. {
  487.     unsigned char    lonibble = v & 0x0f;
  488.     return lonibble + ((lonibble > 9)? ('A'-10): '0');
  489. }
  490.  
  491. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  492.     Name:        immediateError
  493.  
  494.     Input Parameters:    
  495.         
  496.     Output Parameters:
  497.         
  498.     Description:
  499.  
  500.  
  501.  
  502. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  503. static Boolean
  504. immediateError(OSStatus err)
  505. {
  506.     return((err != kUSBPending) && (err != noErr) );
  507. }
  508.  
  509. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  510.     Name:        SetNullUSBParamBlock
  511.  
  512.     Input Parameters:    
  513.         pb                    pointer to USB parameter block
  514.         dev                USB device reference
  515.     Output Parameters:
  516.         pb                    all fields set to default values
  517.  
  518.     Description:
  519.         setup a USB parameter block for use by the current device
  520.  
  521.  
  522.  
  523.  
  524. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  525. static void
  526. SetNullUSBParamBlock( USBDeviceRef dev, USBPB *pb )
  527. {
  528.     pb->qlink = NULL;
  529.     pb->qType = 0;
  530.     pb->pbLength = sizeof(USBPB);
  531.     pb->pbVersion = kUSBCurrentPBVersion;
  532.     pb->usbFlags = 0;
  533.     pb->usbStatus = noErr;
  534.     pb->usbCompletion = (USBCompletion) NULL;
  535.  
  536.     pb->usbReference = dev;
  537. }
  538.  
  539. // BT - 15Jun99, Callback for the suspend call.
  540. static void usbPrintResume(USBPB *pb)
  541. {
  542. IOParamPtr resumePB;
  543. DCtlPtr resumeCtl;
  544. struct usbPrinterPBStruct *resumePrinterPB;
  545.  
  546.     if(pb->usbStatus != noErr)
  547.     {
  548.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver USBPrintDoSuspendResume error", pb->usbStatus);
  549.     }
  550.     else
  551.     {
  552.         currentlyAre = kUSBPrintResumed;
  553.         if(Wpb != nil)
  554.         {
  555.             // We have to restart a waiting write
  556.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver resumeing write", 0);
  557.             resumeCtl = Wctl;
  558.             resumePrinterPB = WpPrinterPB;
  559.             resumePB = Wpb;
  560.             Wpb = nil;
  561.             QueueWrite(resumePB, resumeCtl, resumePrinterPB);
  562.         }
  563.     
  564.         if(Rpb != nil)
  565.         {
  566.             // We have to restart a waiting write
  567.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver resumeing read", 0);
  568.             resumeCtl = Rctl;
  569.             resumePrinterPB = RpPrinterPB;
  570.             resumePB = Rpb;
  571.             Rpb = nil;
  572.             QueueRead(resumePB, resumeCtl, resumePrinterPB);
  573.         }
  574.         if(Cpb != nil)
  575.         {
  576.             // We have to restart a waiting ControlRequest
  577.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver resumeing read", 0);
  578.             resumeCtl = Cctl;
  579.             resumePrinterPB = CpPrinterPB;
  580.             resumePB = Cpb;
  581.             Cpb = nil;
  582.             ControlStatusRequests(resumePB, resumeCtl, resumePrinterPB);
  583.         }
  584.     }
  585.     pb->usbRefcon = 0;
  586. }
  587.  
  588. // BT - 15Jun99, work out if we need to and can suspend or resume and do it.
  589. static USBPrintDoSuspendResume(USBDeviceRef ref)
  590. {
  591. static USBPB pb;
  592. OSStatus err = noErr;
  593.     if(wantToBe != currentlyAre)
  594.     {
  595.         if(currentlyAre == kUSBPrintSuspended)
  596.         {
  597.             USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver resuming device", ref);
  598.             err = USBResumeDeviceByReference(ref);
  599.         }
  600.         else if(wantToBe == kUSBPrintSuspended)
  601.         {
  602.             if( (printerClassRecord.pb.usbCompletion != nil) || 
  603.                 (printerClassRecord.in.usbCompletion != nil) || 
  604.                 (printerClassRecord.out.usbCompletion != nil) )
  605.             {
  606.                 USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver can't suspend, busy", (UInt32) printerClassRecord.pb.usbCompletion);
  607.                 return(noErr);
  608.             }
  609.         
  610.             if(pb.usbRefcon != 0)
  611.             {
  612.                 USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver suspend already in process", err);
  613.                 return(noErr);
  614.             }
  615.             USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver suspending device", ref);
  616.             SetNullUSBParamBlock(ref, &pb);
  617.             pb.usbCompletion = usbPrintResume;
  618.             pb.usbRefcon = 1;
  619.             currentlyAre = kUSBPrintSuspended;
  620.             err = USBSuspendDevice(&pb);
  621.         }
  622.         if( (err != kUSBPending) && (err != noErr) )
  623.         {
  624.             USBExpertStatusLevel(2, ref, "\pUSB print driver USBPrintDoSuspendResume error", err);
  625.         }
  626.     }
  627.     return(noErr);
  628. }
  629.  
  630.  
  631.  
  632.  
  633.  
  634. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  635.     Name:        ParseCapability
  636.  
  637.     Input Parameters:    
  638.         capability            pointer to 1284-1994 capability string
  639.         attribute            pointer to c-string key we're retrieving (terminate with colon)
  640.         *result_length        maximum length of the result 
  641.         
  642.     Output Parameters:
  643.         result                c-string which followed the key and was terminated by semi-colon
  644.                                 (semi-colon has been stripped)
  645.         *result_length        actual length of the result (may be zero)
  646.     
  647.     Description:
  648.         Search for "attribute" in the 1284 "capability" string
  649.         The identifier is terminated with a semi-colon
  650.  
  651.         Return the attribute in result
  652.             null-string if attribute not found.
  653.  
  654.  
  655.  
  656.  
  657.  
  658. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  659. static void
  660. ParseCapability(
  661.     unsigned char    *capability,
  662.     unsigned char    *attribute,
  663.     unsigned char    *result,
  664.     short            *result_length 
  665. )
  666. {
  667.     //
  668.     //    search for "attribute" in the 1284 "capability" string
  669.     //
  670.     //    the identifier is terminated with a semi-colon
  671.     //
  672.     //    return the attribute in result
  673.     //            null-string if attribute not found
  674.     //
  675.     //    <to do> skip blanks, isolate colon, skip blanks
  676.     //
  677.     UInt32                source_length;
  678.     UInt16                target_length;
  679.     unsigned char        *source,
  680.                         *target,
  681.                         *destination;
  682.     Boolean                foundAttribute = false;
  683.     
  684.     //
  685.     //    begin a brute force search
  686.     //
  687.     source = attribute;
  688.     source_length = CStrLen((char *)attribute );
  689.  
  690.     target = capability + 2;    // skip the length
  691.     target_length =  *(UInt16*)capability;
  692.     if (target_length >= 2)
  693.         target_length -= 2;            // don't count the length
  694.     else
  695.         target_length = 0;
  696.         
  697.     while ( target_length >= source_length )
  698.     {
  699.         if ( memcmp( source, target, source_length ) == 0 ){
  700.             foundAttribute = true;
  701.             break;
  702.         }
  703.         --target_length;
  704.         ++target;
  705.     }
  706.     
  707.     *result = '\0';    // empty result
  708.  
  709.     if (foundAttribute)  // we found the attribute string we are looking for, let's copy the result
  710.     {
  711.         destination = result;
  712.     
  713.         target += source_length;
  714.         target_length -= source_length;    // skip the attribute string
  715.     
  716.         if ( target_length > 0 )
  717.         {
  718.             //
  719.             //    we found the attribute in the capability string
  720.             //
  721.             while ( destination - result < *result_length )    // arbitrarily limit reply
  722.             {
  723.                 if ( *target == ';' || target_length == 0)
  724.                     break;
  725.                 *destination++ = *target++;        // copy a byte of attribute over
  726.                 --target_length;
  727.             }
  728.             *destination++ = '\0';                        // trailing NUL
  729.             *result_length = destination - result;    // report the length of the data (with trailing NUL)
  730.         }
  731.     }
  732. }
  733.  
  734.  
  735. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  736.     Name:        GetClass
  737.  
  738.     Input Parameters:    
  739.         capability            pointer to 1284-1994 capability string
  740.         *result_length        maximum length of the result 
  741.         
  742.     Output Parameters:
  743.         result                c-string extracted from the MODEL key
  744.         *result_length        actual length of the result  (may be zero)
  745.         
  746.     Description:
  747.         CLASS is a Microsoft extension to the 1284-capability string
  748.         if we don't find it
  749.             we assume that the device is a printer
  750.         Since the USB hardware has already indicated this, we're really allowing
  751.         devices which aren't printers to be reached via the DRVRs we've installed.
  752.  
  753.  
  754.  
  755.  
  756. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  757. static void
  758. GetClass(
  759.     unsigned char    *capability,
  760.     unsigned char    *result,
  761.     short            *result_length
  762. )
  763. {
  764.     //
  765.     //    We supply the upper-case PRINTER to be consistent with 1284-1994
  766.     //        if we don't find a class.
  767.     //
  768.     ParseCapability( capability, (unsigned char *) "CLASS:", result, result_length);
  769.     if ( *result == '\0' )
  770.         ParseCapability( capability, (unsigned char *) "CLS:", result, result_length);
  771.     if ( *result == '\0' )
  772.         CStrCopy( (char *)result, "PRINTER" );
  773. }
  774.  
  775.  
  776. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  777.     Name:        GetModel
  778.  
  779.     Input Parameters:    
  780.         capability            pointer to 1284-1994 capability string
  781.         *result_length        maximum length of the result 
  782.         
  783.     Output Parameters:
  784.         result                c-string extracted from the MODEL key
  785.         *result_length        actual length of the result  (may be zero)
  786.             
  787.     Description:
  788.         MODEL is a required field of the 1284-capability string
  789.         MODEL may be abbreviated MDL
  790.  
  791.  
  792.  
  793.  
  794. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  795. static void
  796. GetModel(
  797.     unsigned char    *capability, 
  798.     unsigned char    *result,
  799.     short            *result_length
  800. )
  801. {
  802.     //
  803.     //    Most manufacturers abbreviate, so we search for MDL first
  804.     //
  805.     ParseCapability( capability, (unsigned char *) "MDL:", result, result_length );
  806.     if ( *result == '\0' )
  807.         ParseCapability( capability, (unsigned char *) "MODEL:", result, result_length );
  808. }
  809.  
  810.  
  811. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  812.     Name:        GetCommandSet
  813.  
  814.     Input Parameters:    
  815.         
  816.     Output Parameters:
  817.         
  818.     Description:
  819.  
  820.  
  821.  
  822.  
  823. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  824. static void
  825. GetCommandSet(
  826.     unsigned char    *capability, 
  827.     unsigned char    *result,
  828.     short              *result_length
  829. )
  830. {
  831.     //
  832.     //    COMMAND-SET is a required field of the 1284-capability string
  833.     //    COMMAND-SET may be abbreviated CMD
  834.     //
  835.     ParseCapability( capability, (unsigned char *) "CMD:", result, result_length );
  836.     if ( *result == '\0' )
  837.         ParseCapability( capability, (unsigned char *) "COMMAND SET:", result, result_length );
  838. }
  839.  
  840. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  841.     Name:        GetManufacturer
  842.  
  843.     Input Parameters:    
  844.         
  845.     Output Parameters:
  846.         
  847.     Description:
  848.  
  849.  
  850.  
  851. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  852. static void
  853. GetManufacturer(
  854.     unsigned char *capability, 
  855.     unsigned char *result,
  856.     short *result_length
  857. )
  858. {
  859.     //
  860.     //    MANUFACTURER is a required field of the 1284-capability string
  861.     //    MANUFACTURER may be abbreviated MFG
  862.     //
  863.     ParseCapability( capability, (unsigned char *) "MFG:", result, result_length );
  864.     if ( *result == '\0' )
  865.         ParseCapability( capability, (unsigned char *) "MANUFACTURER:", result, result_length );
  866.     if ( *result == '\0' )
  867.         ParseCapability( capability, (unsigned char *) "HMFG:", result, result_length );
  868. }
  869.  
  870.  
  871. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  872.     Name:        DeregisterDevice
  873.  
  874.     Input Parameters:    
  875.         pPrinterPB
  876.  
  877.     Output Parameters:
  878.         <none>
  879.         
  880.     Description:
  881.         remove the device from the name registry
  882.  
  883.  
  884.  
  885.  
  886.  
  887. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  888. #define kMinNameLength    27
  889. #define kMinModelLength    25
  890. #define kMinClassLength    23
  891.  
  892. static OSStatus
  893. DeregisterDevice( struct usbPrinterPBStruct *pPrinterPB )
  894. {
  895. RegEntryID            self, child, parent;
  896. RegEntryIter         cookie;
  897.  
  898. OSStatus    err = noErr;
  899. Str255        tempStr1,tempStr2;
  900. UInt32        nameLength, modelLength,devclassLength;
  901. Boolean     done = false;
  902.  
  903.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Removing the printer from the name registry", 0 );
  904.     // delete the printer node
  905.     // print out the printer's name (which is the same as the node name)
  906.     nameLength = CStrLen((char *)pPrinterPB->name);
  907.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer name:  "));
  908.     CStrCat((char *)tempStr1, (char *)pPrinterPB->name);
  909.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  910.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, nameLength );
  911.     
  912.     // locate the model node (parent of printer), and delete it if the printer has no siblings
  913.     if (nameLength<kMinNameLength)
  914.     {
  915.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer name string is not long enough!", nameLength);
  916.     }
  917.     else
  918.     {
  919.         RegistryEntryIDInit( &self );
  920.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  921.         if ( err == noErr )
  922.         {    
  923.             err = RegistryEntryDelete( &self);
  924.         }
  925.         else
  926.         {
  927.             USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Printer node not found!", err );
  928.         }
  929.         RegistryEntryIDDispose(&self);
  930.         
  931.     }
  932.  
  933.  
  934.     // print out the printer's model (which is the same as the node's parent)
  935.     modelLength = CStrLen((char *)pPrinterPB->model);
  936.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer model: "));
  937.     CStrCat((char *)tempStr1, (char *)pPrinterPB->model);
  938.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  939.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, modelLength );
  940.     
  941.  
  942.     // locate the model node (parent of printer), and delete it if the printer has no siblings
  943.     if (modelLength<kMinModelLength)
  944.     {
  945.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer model string is not long enough!", modelLength);
  946.     }
  947.     else
  948.     {
  949.         RegistryEntryIDInit( &parent );
  950.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->model , &parent );
  951.         if ( err == noErr )
  952.         {    
  953.             RegistryEntryIDInit(&child);
  954.             
  955.             err = RegistryEntryIterateCreate(&cookie);
  956.             if (err == noErr)
  957.                 err = RegistryEntryIterateSet(&cookie, &parent);
  958.             if (err == noErr)
  959.                 err = RegistryEntryIterate(&cookie, kRegIterChildren, &child, &done);
  960.             if ((err == noErr) && done)
  961.             {
  962.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"No siblings detected, so delete the parent of printer", 0 );
  963.                 err = RegistryEntryDelete(&parent);
  964.             }
  965.             else
  966.             {
  967.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Siblings (or error) detected.  Leaving parent in place", err );
  968.             }
  969.             RegistryEntryIterateDispose(&cookie);
  970.         }
  971.         else
  972.         {
  973.             USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Parent node not found!", err );
  974.         }
  975.         RegistryEntryIDDispose(&parent);
  976.     }
  977.     
  978.     // print out the printer's model (which is the same as the node's parent)
  979.     devclassLength = CStrLen((char *)pPrinterPB->devclass);
  980.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer class: "));
  981.     CStrCat((char *)tempStr1, (char *)pPrinterPB->devclass);
  982.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  983.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, devclassLength );
  984.     
  985.  
  986.     // locate the class node (parent of model), and delete it if the class has no siblings
  987.     if (devclassLength<kMinClassLength)
  988.     {
  989.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer class string not long enough!", devclassLength);
  990.     }
  991.     else
  992.     {
  993.         RegistryEntryIDInit( &parent );
  994.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->devclass , &parent );
  995.         if ( err == noErr )
  996.         {    
  997.             RegistryEntryIDInit(&child);
  998.             
  999.             err = RegistryEntryIterateCreate(&cookie);
  1000.             if (err == noErr)
  1001.                 err = RegistryEntryIterateSet(&cookie, &parent);
  1002.             if (err == noErr)
  1003.                 err = RegistryEntryIterate(&cookie, kRegIterChildren, &child, &done);
  1004.             if ((err == noErr) && done)
  1005.             {
  1006.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"No models found, so delete the class node", 0 );
  1007.                 err = RegistryEntryDelete(&parent);
  1008.             }
  1009.             else
  1010.             {
  1011.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Models detected.  Leaving class nodes in place", err );
  1012.             }
  1013.             RegistryEntryIterateDispose(&cookie);
  1014.         }
  1015.         else
  1016.         {
  1017.             USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Parent node not found!", err );
  1018.         }
  1019.         RegistryEntryIDDispose(&parent);
  1020.     }
  1021.     
  1022.     return err;
  1023. }
  1024.  
  1025. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1026.     Name:        RegisterDevice
  1027.  
  1028.     Input Parameters:    
  1029.         pPrinterPB
  1030.  
  1031.     Output Parameters:
  1032.         <none>
  1033.         
  1034.     Description:
  1035.         add the device into the name registry; we can't insert just the node
  1036.         if the parent nodes aren't present.
  1037.  
  1038.         if it isn't present
  1039.             insert the device CLASS into the registry
  1040.         if it isn't present
  1041.             insert the device MODEL into the registry
  1042.         finally insert the device itself into the registry
  1043.             we're careful to rename multiple devices
  1044.  
  1045.  
  1046.  
  1047.  
  1048.  
  1049.  
  1050.  
  1051.  
  1052.  
  1053. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1054. static OSStatus
  1055. RegisterDevice( struct usbPrinterPBStruct *pPrinterPB )
  1056. {
  1057.     //
  1058.     //    add the device into the name registry
  1059.     //    if it isn't present
  1060.     //        insert the device CLASS into the registry
  1061.     //    if it isn't present
  1062.     //        insert the device MODEL into the registry
  1063.     //    finally insert the device itself into the registry
  1064.     //        we're careful to rename multiple devices
  1065.     //
  1066. Str255        identification,
  1067.                 devclass,
  1068.                 model,
  1069.                 nameregmodel,
  1070.                 commands,
  1071.                 tempstr;
  1072.                 
  1073. RegEntryID    parent, where, self;
  1074.  
  1075. OSStatus        err;
  1076.  
  1077. short            model_length,
  1078.                 command_length,
  1079.                 class_length;
  1080.  
  1081.  
  1082.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Adding the printer to the name registry", 0 );
  1083.     CStrCopy((char *)pPrinterPB->devclass, "");
  1084.     CStrCopy((char *)pPrinterPB->model, "");
  1085.     CStrCopy((char *)pPrinterPB->name, "");
  1086.  
  1087.     command_length = sizeof(commands);
  1088.     GetCommandSet(pPrinterPB->pCapabilityString, commands, &command_length );
  1089.  
  1090.  
  1091.     // get device class and add it to the name registry.  Typically PRINTER or Printer
  1092.     class_length = sizeof(devclass);
  1093.     GetClass( pPrinterPB->pCapabilityString, devclass, &class_length );
  1094.     // force the device class to all uppercase.
  1095.     ForceUpperStr((char *)devclass);
  1096.     
  1097.     CStrCopy( (char *)pPrinterPB->devclass, (char *)"Devices:device-tree:" );
  1098.     CStrCat( (char *)pPrinterPB->devclass, (char *)devclass );
  1099.     
  1100.     RegistryEntryIDInit( &where );
  1101.     err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->devclass, &where );
  1102.     if ( err == nrPathNotFound ) 
  1103.     {
  1104.         //    class not in registry
  1105.         //        create a node for all devices of this CLASS
  1106.         //
  1107.         RegistryEntryIDInit( &parent );
  1108.         err = RegistryCStrEntryLookup( nil, "Devices:device-tree:" , &parent );
  1109.         if ( err == noErr )
  1110.             err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->devclass, &where );
  1111.         RegistryEntryIDDispose(&parent);
  1112.  
  1113.     }
  1114.     
  1115.     CStrToPStr(tempstr, (char *)pPrinterPB->devclass);
  1116.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, 0 );
  1117.     
  1118.     //
  1119.     //    add this model into the name registry of this class
  1120.     //
  1121.     if ( err == noErr )
  1122.     {
  1123.         model_length = sizeof(model);
  1124.         GetModel( pPrinterPB->pCapabilityString, model, &model_length );
  1125.         CStrCopy( (char *)nameregmodel, (char *)model);
  1126.         MakeNameRegistrySafeStr((char *)nameregmodel);
  1127.         if ( *model != '\0' )
  1128.         {
  1129.             CStrCopy( (char *)pPrinterPB->model, "Devices:device-tree:" );
  1130.             CStrCat( (char *)pPrinterPB->model, (char *)devclass );
  1131.             CStrCat( (char *)pPrinterPB->model, ":" );
  1132.             if ( *model == '\0'  )
  1133.             {
  1134.                 CStrCat( (char *)pPrinterPB->model, (char *)"USB_PRINTERCLASS" );
  1135.             }
  1136.             else
  1137.             {
  1138.                 CStrCat( (char *)pPrinterPB->model, (char *)nameregmodel );
  1139.             }
  1140.             RegistryEntryIDInit( &self );
  1141.             err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->model , &self );
  1142.             if ( err != noErr )
  1143.             {
  1144.                 // model not in registry
  1145.                 err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->model, &self );
  1146.             }
  1147.             
  1148.             RegistryEntryIDDispose(&self);
  1149.         }
  1150.         CStrToPStr(tempstr, (char *)pPrinterPB->model);
  1151.         USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, 0 );
  1152.     }
  1153.     
  1154.     //
  1155.     //    add this instance of this model of this class
  1156.     //        into the name registry
  1157.     //
  1158.     if ( *model == '\0'  )
  1159.     {
  1160.         //
  1161.         //    possibly the cable isn't firmly connected or the printer isn't switched on
  1162.         //
  1163.         err = kUSBInternalErr;
  1164.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Model undefined", 0);
  1165.     }
  1166.     if ( err == noErr )
  1167.     {
  1168.         //
  1169.         //    start off by identifying the device simply by the model name
  1170.         //        increment the numeric suffix until we successfully registry the device
  1171.         //
  1172.         Str32    suffix;
  1173.         short    numeric_suffix;
  1174.  
  1175.         CStrCopy( (char *)identification, (char *)nameregmodel );
  1176.         RegistryEntryIDInit( &self );
  1177.         for ( numeric_suffix = 1; numeric_suffix < MAX_SUFFIX; ++numeric_suffix )
  1178.         {
  1179.             CStrCopy( (char *)pPrinterPB->name, "Devices:device-tree:" );
  1180.             CStrCat( (char *)pPrinterPB->name, (char *)devclass );
  1181.             CStrCat( (char *)pPrinterPB->name, ":" );
  1182.             CStrCat( (char *)pPrinterPB->name, (char *)nameregmodel );
  1183.             CStrCat( (char *)pPrinterPB->name, ":" );
  1184.             CStrCat( (char *)pPrinterPB->name, (char *)identification );
  1185.             err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  1186.             if ( err != noErr )
  1187.             {
  1188.                 // enter device in registry
  1189.                 err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->name, &self );
  1190.                 if ( err == noErr )
  1191.                 {
  1192.                     CStrCopy( (char *)identification, (char *)model );
  1193.                     if (numeric_suffix > 1)
  1194.                     {
  1195.                         sprintf( (char *)suffix, " %d", numeric_suffix-1 );
  1196.                         CStrCat( (char *)identification, (char *)suffix );
  1197.                     }
  1198.                     err = RegistryPropertyCreate( &self, "modelName", identification, strlen((char *)identification) );
  1199.                 }
  1200.                 if ( err == noErr )
  1201.                     err = RegistryPropertyCreate( &self, "drvrOut", &pPrinterPB->driverOutName, 1 + pPrinterPB->driverOutName[0] );
  1202.                 if ( err == noErr )
  1203.                     err = RegistryPropertyCreate( &self, "outRef", &pPrinterPB->outRefNum, sizeof(pPrinterPB->outRefNum) );
  1204.                 
  1205.                 if (pPrinterPB->printerProtocol != kUSBPrinterUnidirectionalProtocol)
  1206.                 {
  1207.                     if ( err == noErr )
  1208.                         err = RegistryPropertyCreate( &self, "drvrIn", &pPrinterPB->driverInName, 1 + pPrinterPB->driverInName[0] );
  1209.                     if ( err == noErr )
  1210.                         err = RegistryPropertyCreate( &self, "inRef", &pPrinterPB->inRefNum, sizeof(pPrinterPB->inRefNum) );
  1211.                 }
  1212.                 if ( err == noErr )
  1213.                     err = RegistryPropertyCreate( &self, "privateData", &pPrinterPB, sizeof(pPrinterPB) );
  1214.                 if ( err == noErr )
  1215.                     err = RegistryPropertyCreate( &self, "read", &pPrinterPB->r, sizeof(QueueUSBReadUPP) );
  1216.                 if ( err == noErr )
  1217.                     err = RegistryPropertyCreate( &self, "write", &pPrinterPB->w, sizeof(QueueUSBWriteUPP) );
  1218.                 if ( err == noErr && *commands != '\0' )
  1219.                     err = RegistryPropertyCreate( &self, "command-set", &commands, command_length );
  1220.                 break;
  1221.             }
  1222.             //
  1223.             //    if this name didn't succeed
  1224.             //        try the next numeric suffix
  1225.             //
  1226.             sprintf( (char *)suffix, " %d", numeric_suffix );
  1227.             CStrCopy( (char *)identification, (char *)nameregmodel );
  1228.             CStrCat( (char *)identification, (char *)suffix );
  1229.         }
  1230.         RegistryEntryIDDispose(&self);
  1231.     }
  1232.     pPrinterPB->printerRegistered = true;
  1233.     
  1234.     CStrToPStr((unsigned char *)tempstr, (char const *)pPrinterPB->name );
  1235.     
  1236.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Added printer to name registry", 0 );
  1237.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, err );
  1238.     RegistryEntryIDDispose(&where);
  1239.  
  1240.     LOGGING( logfile = fopen( "USBPrinter.log", "wb+" ) );
  1241.     return err;
  1242. }
  1243.  
  1244. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1245.     Name:        LoadResources
  1246.  
  1247.     Input Parameters:
  1248.         pPrinterPB            pointer to class driver's private storage
  1249.         
  1250.     Output Parameters:
  1251.         OSStatus                resource load error
  1252.         
  1253.     Description:
  1254.         Initialize time is the only safe time to to load resources from our file.
  1255.         Here's where we load resources and detach them from the resource manager.
  1256.         Later we'll use these private copies instead of GetResource calls.
  1257.         
  1258.         Using the file spec that we got from the CFMInitialization routine, open
  1259.         our resource fork.
  1260.  
  1261.  
  1262.  
  1263.  
  1264. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1265. static OSStatus
  1266. LoadResources( struct usbPrinterPBStruct *pPrinterPB )
  1267. {
  1268.     short            rf = -1;                // class driver resource fork
  1269.     OSStatus        err;
  1270.  
  1271.     //
  1272.     //    open the resource fork of this class driver
  1273.     //
  1274.     rf = FSpOpenResFile( &printerClassDriverFileSpec,fsRdPerm );
  1275.     err = ResError();
  1276.     
  1277.     //
  1278.     //    load the DRVR that we'll stick in the unit table
  1279.     //
  1280.     pPrinterPB->hDrvr = NULL;
  1281.     if ( err == noErr )
  1282.     {
  1283.         pPrinterPB->hDrvr = (DRVRHeaderHandle) Get1Resource( 'DRVR',  kUSBParallelDrvrRsrcID );
  1284.         if ( pPrinterPB->hDrvr != NULL )
  1285.             DetachResource( (Handle) pPrinterPB->hDrvr );
  1286.         err = ResError();
  1287.     }
  1288.     
  1289.     if ( rf != -1 )
  1290.         CloseResFile( rf );
  1291.     
  1292.     return err;
  1293. }
  1294.  
  1295. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1296.     Name:        InstallDrivers
  1297.  
  1298.     Input Parameters:
  1299.         pPrinterPB
  1300.         
  1301.     Output Parameters:
  1302.         OSStatus            error code
  1303.         
  1304.     Description:
  1305.         install read and write drivers in the unit table
  1306.             we have separate drivers so that we can support a full-duplex protocol
  1307.         rename the driver we just installed (so multiple copies don't conflict)
  1308.         We use the DRVR -refnum-1 so that the driver name has the same hex chars
  1309.             as the driver number (for manual verification in MacsBug)
  1310.  
  1311.  
  1312.  
  1313.  
  1314.  
  1315.  
  1316. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1317. static OSStatus
  1318. InstallDrivers( struct usbPrinterPBStruct *pPrinterPB )
  1319. {
  1320.     //
  1321.     //    install the driver in the unit table
  1322.     //    rename the driver we just installed (so multiple copies don't conflict)
  1323.     //    
  1324.     short            refNum;                // DRVR refNum
  1325.     OSStatus        err =  paramErr;    // couldn't find driver
  1326.  
  1327.     if ( pPrinterPB->hDrvr != NULL )
  1328.         err = TradInstallDriverFromHandle( pPrinterPB->hDrvr, kMinDrvrUnitNumber, TradHighestUnitNumber() + 1, &pPrinterPB->outRefNum );
  1329.  
  1330.     if ( err == noErr )
  1331.     {
  1332.         UnitNumber        unit;
  1333.         DriverFlags        flags;
  1334.         DRVRHeaderPtr    hdr;
  1335.         unsigned char    *suffix,        // append "In" and "Out"
  1336.                             *infix;        // driver reference number follows the ".USB"
  1337.  
  1338.         TradGetDriverInformation( pPrinterPB->outRefNum, &unit, &flags, pPrinterPB->driverOutName, &hdr );
  1339.         BlockMove( pPrinterPB->driverOutName, pPrinterPB->driverInName, 1 + pPrinterPB->driverOutName[0] );
  1340.         
  1341.         suffix = pPrinterPB->driverOutName + pPrinterPB->driverOutName[0] - 2;
  1342.         infix = pPrinterPB->driverOutName + kDrvrFirstDigit;
  1343.         infix[0] = HiHex( -pPrinterPB->outRefNum -1 );
  1344.         infix[1] = LoHex( -pPrinterPB->outRefNum -1 );
  1345.         suffix[0] = 'O';
  1346.         suffix[1] = 'u';
  1347.         suffix[2] = 't';
  1348.         TradRenameDriver( pPrinterPB->outRefNum, pPrinterPB->driverOutName );
  1349.         //
  1350.         //    set the driver data to point to our parameter block
  1351.         //
  1352.         err = OpenDriver( pPrinterPB->driverOutName, &refNum );
  1353.         if ( err == noErr )
  1354.         {
  1355.             struct usbPrinterPBStruct *param = pPrinterPB;
  1356.             err = Control( refNum, kDrvrPrivateSetStorage, ¶m );
  1357.             CloseDriver( refNum );
  1358.         }
  1359.         err = TradInstallDriverFromHandle( pPrinterPB->hDrvr, kMinDrvrUnitNumber, TradHighestUnitNumber() + 1, &pPrinterPB->inRefNum );
  1360.         if ( err == noErr )
  1361.         {
  1362.             
  1363.             suffix = pPrinterPB->driverInName + pPrinterPB->driverInName[0] - 1;
  1364.             infix = pPrinterPB->driverInName + kDrvrFirstDigit;
  1365.             infix[0] = HiHex( -pPrinterPB->inRefNum -1 );
  1366.             infix[1] = LoHex( -pPrinterPB->inRefNum -1 );
  1367.             suffix[0] = 'I';
  1368.             suffix[1] = 'n';
  1369.             TradRenameDriver( pPrinterPB->inRefNum, pPrinterPB->driverInName );
  1370.             //
  1371.             //    set the driver data to point to our parameter block
  1372.             //
  1373.             err = OpenDriver( pPrinterPB->driverInName, &refNum );
  1374.             if ( err == noErr )
  1375.             {
  1376.                 struct usbPrinterPBStruct *param = pPrinterPB;
  1377.                 err = Control( refNum, kDrvrPrivateSetStorage, ¶m );
  1378.                 CloseDriver( refNum );
  1379.             }
  1380.         }
  1381.     }
  1382.     
  1383.     return err;
  1384. }
  1385.  
  1386. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1387.     Name:        GetCapability
  1388.  
  1389.     Input Parameters:    
  1390.         
  1391.     Output Parameters:
  1392.         
  1393.     Description:
  1394.         Asynchronous completion.
  1395.  
  1396.  
  1397.  
  1398. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1399. static void
  1400. GetCapability( struct usbPrinterPBStruct *pPrinterPB, unsigned char *p, short length )
  1401. {
  1402.     //
  1403.     //    queue a transaction to retrieve the 1284 capability string
  1404.     //        we must have assigned the interface by this point since the capability string
  1405.     //        may vary with the interface
  1406.     //
  1407.     OSStatus        err;
  1408.     USBPB            *pb = &pPrinterPB->pb;
  1409.  
  1410.     SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  1411.     
  1412.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  1413.     pb->usbBuffer = 0;
  1414.     pb->usbActCount = 0;
  1415.     pb->usbReqCount = 0;
  1416.  
  1417.     pb->usb.cntl.BRequest = kUSBPrintClassGetDeviceID;
  1418.     pb->usb.cntl.WValue = 0;            // configuration
  1419.     pb->usb.cntl.WIndex = (pPrinterPB->interfaceNumber<<8) | pPrinterPB->alternateSetting;
  1420.  
  1421.     pb->usbReqCount = length;
  1422.     pb->usbBuffer = p;
  1423.  
  1424.     pb->usbRefcon |= kTransactionPending;
  1425.     pb->usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  1426.     err = USBDeviceRequest(pb);
  1427.     if(immediateError(err))
  1428.     {
  1429.         USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"GetCapability", 0);
  1430.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1431.         pb->usbRefcon |= kReturnFromDriver;
  1432.     }
  1433. }
  1434.  
  1435. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1436.     Name:        IsLucentCable
  1437.  
  1438.     Input Parameters:    
  1439.         dev            USB device descriptor
  1440.         
  1441.     Output Parameters:
  1442.         Return 1 if the USB device is a USB-parallel cable
  1443.         
  1444.     Description:
  1445.         
  1446.  
  1447.  
  1448.  
  1449. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1450. static short
  1451. IsLucentCable( USBDeviceDescriptor    *dev )
  1452. {
  1453.     return ( USBToHostWord(dev->vendor) == 0x47E && USBToHostWord(dev->product) == 0x1001 )? 1: 0;
  1454. }
  1455.  
  1456.  
  1457. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1458.     Name:        GetInterface
  1459.  
  1460.     Input Parameters:    
  1461.         
  1462.     Output Parameters:
  1463.         
  1464.     Description:
  1465.         Asynchronous completion.
  1466.  
  1467.  
  1468.  
  1469. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1470. static void
  1471. GetInterface( USBPB *pb, UInt8 *alt )
  1472. {
  1473.     //
  1474.     //    make sure we account for any alternate interface currently in use by the device
  1475.     //
  1476.     OSStatus    err;
  1477.  
  1478.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBStandard, kUSBInterface);
  1479.  
  1480.     pb->usb.cntl.BRequest = kUSBRqGetInterface;
  1481.     pb->usb.cntl.WValue = 0; 
  1482.     pb->usb.cntl.WIndex = 0;
  1483.  
  1484.     pb->usbReqCount = sizeof(UInt8);        // single byte is requested
  1485.     pb->usbBuffer = alt;
  1486.  
  1487.     pb->usbStatus = 0;
  1488.     pb->usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  1489.     pb->usbRefcon |= kTransactionPending;
  1490.  
  1491.     err = USBDeviceRequest(pb);
  1492.     if(immediateError(err))
  1493.     {
  1494.         USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"GetInterface", 0);
  1495.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1496.         pb->usbRefcon |= kReturnFromDriver;
  1497.     }
  1498. }
  1499.  
  1500.  
  1501. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1502.     Name:        ReadCompletion
  1503.  
  1504.     Input Parameters:    
  1505.         pb                        USB parameter block
  1506.         
  1507.     Output Parameters:
  1508.         <none>
  1509.  
  1510.     Description:
  1511.         USB read requests complete here.
  1512.         We dequeue the MacOS DRVR read requests
  1513.  
  1514.  
  1515.  
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1522. static void
  1523. ReadCompletion(USBPB *pb)
  1524. {
  1525.     //    call the user completion routine
  1526.     struct usbPrinterPBStruct
  1527.             *pPrinterPB =  (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1528.     IOParamPtr     clientParam = pPrinterPB->readDrvr.pb;
  1529.     OSStatus        err = pb->usbStatus;
  1530.     DCtlPtr            ctlLocal;
  1531.  
  1532. #if MACSBUG_ON_READ_COMPLETE
  1533.     Str255    text;
  1534.     sprintf( (char *)text, " PrinterClass Read Complete(%d): %d", pb->usbStatus, pb->usbActCount );
  1535.     text[0] = CStrLen((char *)text); // c2pstr
  1536.     DebugStr( text );
  1537. #endif
  1538.  
  1539. #if DOUBLE_BUFFER
  1540.     //
  1541.     //    copy the user data from our page aligned buffer
  1542.     //
  1543.     USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion - bytes read  " , (UInt32)pb->usbActCount );
  1544.  
  1545.     if ( pb->usbActCount > 0 )
  1546.         BlockCopy( pPrinterPB->pageReadAlignedBuffer, clientParam->ioBuffer + clientParam->ioActCount, pb->usbActCount );
  1547. #endif
  1548.     //    update the amount of data actually transferred
  1549.     clientParam->ioActCount += pb->usbActCount;
  1550.  
  1551.     switch( pb->usbStatus )
  1552.     {
  1553.         //
  1554.         //    only retry low level hardware problems
  1555.         //        note: abort transactions will end up here as well
  1556.         //
  1557.     case kUSBLinkErr:
  1558.     case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  1559.     case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  1560.     case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  1561.     case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  1562.     case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  1563.     case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  1564.         if (  --(pPrinterPB->readRetryCount) >= 0 ) // = is there so we don't retry clear endpoints forever
  1565.         {
  1566.             if(pPrinterPB->readStatus == noErr)
  1567.             {
  1568.                 pPrinterPB->readStatus = pb->usbStatus;
  1569.             }
  1570.             // we got an error, and we still want to retry, clear any stalls
  1571.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion retry" , pb->usbStatus );
  1572.             USBClearPipeStallByReference(pPrinterPB->readPipeRef);
  1573.             pb->usbStatus = noErr;
  1574.  
  1575.             
  1576.             USBExpertStatusLevel(3, pb->usbReference, kPStrPrinterDriverName"**** ReadCompletion clearing endpoint halt *****" , pb->usbStatus );
  1577.             ClearEndpointHalt(pb);    // Sets up PB
  1578.             USBDeviceRequest(pb);
  1579.             return;
  1580.         }
  1581.         break;
  1582.     case kUSBAbortedError:                        /* user cancel, or hot unplug */
  1583.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion abortedError" , pb->usbStatus );
  1584.         USBClearPipeStallByReference(pPrinterPB->readPipeRef);
  1585.         USBClearPipeStallByReference(pPrinterPB->deviceRef);
  1586.         break;
  1587.         //
  1588.         //    any other error will be reported to the client
  1589.         //
  1590.     default:
  1591.     case noErr:
  1592.         break;
  1593.     }
  1594.     
  1595. //    (pPrinterPB->readStatus != noErr)    
  1596. //or 
  1597. //    (pPrinterPB->readStatus == noErr) and (pb->usbActCount == pb->usbReqCount)
  1598.  
  1599. //                  read Status == noErr
  1600. //                     true        false
  1601. //
  1602. //  act=req  t      r         r
  1603. //
  1604. //           f      x         r
  1605.  
  1606.     
  1607.     if ( (pb->usbStatus == noErr) &&                                 // there were no problems
  1608.          (pPrinterPB->readRetryCount > 0) &&                        // there were no enough problems
  1609.          
  1610.         ( (pPrinterPB->readStatus != noErr) ||
  1611.          (pb->usbActCount == pb->usbReqCount)  ) &&                    // we got all the data we requested
  1612. // BT don't do this or we'll never retry read errors. However we need to do this to finish short packets.
  1613. //  
  1614.  
  1615.         (clientParam->ioActCount < clientParam->ioReqCount) )        // we still want more data
  1616.     {
  1617.         //
  1618.         //    haven't finish the client's request
  1619.         //        update the pointers and start another bulk read transaction
  1620.         //
  1621. #if LOCK_MEMORY
  1622.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1623.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion UnlockMem failed" ) );
  1624. #endif
  1625.         pb->usbBuffer = clientParam->ioBuffer + clientParam->ioActCount;
  1626.         pb->usbReqCount = clientParam->ioReqCount - clientParam->ioActCount;
  1627. #if MAX_USB_TRANSFER_SIZE
  1628.         if ( pb->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1629.             pb->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1630. #endif
  1631. #if DOUBLE_BUFFER
  1632.         //
  1633.         //    make sure we have enough room in our buffer
  1634.         //
  1635.         if ( pb->usbReqCount > pPrinterPB->pageReadAlignedBufferSize )
  1636.             pb->usbReqCount = pPrinterPB->pageReadAlignedBufferSize;
  1637.         pb->usbBuffer = pPrinterPB->pageReadAlignedBuffer;
  1638. #endif
  1639.  
  1640.         pPrinterPB->readStatus = noErr;
  1641. #if LOCK_MEMORY
  1642.         err = LockMemory( pb->usbBuffer, pb->usbReqCount );
  1643.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion LockMem failed" ) );
  1644.         if ( err == noErr )
  1645. #endif
  1646.             err = SafeUSBBulkRead( pb );    // Note this is probably hanging off the if above.
  1647.         if ( immediateError(err) )
  1648.         {
  1649.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion finish immed err" , err );
  1650.  
  1651.             pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1652.             if ( pPrinterPB->readDrvr.ctl != NULL )
  1653.             {
  1654.                 ctlLocal = pPrinterPB->readDrvr.ctl;
  1655.                 pPrinterPB->readDrvr.ctl = NULL;
  1656.                 CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, err, clientParam, ctlLocal ); 
  1657.             }
  1658.         }
  1659.     }
  1660.     else
  1661.     {
  1662.         if(pPrinterPB->readStatus != noErr)
  1663.         {
  1664.             pb->usbStatus = pPrinterPB->readStatus;
  1665.         }
  1666.         //
  1667.         //        either we have an error which we're not retrying
  1668.         //            or we successfully completed
  1669.         //
  1670. #if LOCK_MEMORY
  1671.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1672.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion concluded UnlockMem failed" ) );
  1673. #endif
  1674.         IF_DEBUG( if (pb->usbStatus != noErr) USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion Error" , pb->usbStatus ) );
  1675.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1676.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"readDrvr.ctl = " , (UInt32)pPrinterPB->readDrvr.ctl );
  1677.         if ( pPrinterPB->readDrvr.ctl != NULL )
  1678.         {
  1679.             ctlLocal = pPrinterPB->readDrvr.ctl;
  1680.             pPrinterPB->readDrvr.ctl = NULL;
  1681.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, ctlLocal); 
  1682.         }
  1683.         else
  1684.         {
  1685.             IF_DEBUG( DebugStr( kPStrPrinterDriverName"ReadCompletion() pPrinterPB->readDrvr.ctl == NULL" ) );
  1686.         }
  1687.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB PRint, read completion do suspend resume" , pb->usbReference);
  1688.         USBPrintDoSuspendResume(pPrinterPB->interfaceRef);
  1689.     }
  1690. }
  1691.  
  1692.  
  1693. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1694.     Name:        WriteCompletion
  1695.  
  1696.     Input Parameters:    
  1697.         pb                        USB parameter block
  1698.         
  1699.     Output Parameters:
  1700.         <none>
  1701.  
  1702.     Description:
  1703.         USB write requests complete here.
  1704.         We dequeue the MacOS DRVR write requests
  1705.  
  1706.         when breaking up transactions we use ioActCount to determine how much remains 
  1707.                 of the original request and where the next request begins
  1708.         if we've failed with a USB error
  1709.             usbActCount indicates how much data has been transferred with the current request
  1710.             and if the retry count hasn't been exceeded
  1711.                 we proceed as if we'd just requested that much in this transactions
  1712.         note the retry count is cumulative for the original client request
  1713.             not for each usb transaction
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720.  
  1721.  
  1722.  
  1723.  
  1724. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1725. static void
  1726. WriteCompletion(USBPB *pb)
  1727. {
  1728.     //    call the user completion routine
  1729.     struct usbPrinterPBStruct
  1730.                     *pPrinterPB =  (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1731.     IOParamPtr     clientParam = pPrinterPB->writeDrvr.pb;
  1732.     DCtlPtr            ctlLocal;
  1733.     OSStatus        err = pb->usbStatus;
  1734.  
  1735. #if MACSBUG_ON_WRITE_COMPLETE
  1736.     Str255    text;
  1737.     sprintf( (char *)text, " PrinterClass Write Complete(%d): %d", pb->usbStatus, pb->usbActCount );
  1738.     text[0] = CStrLen((char *)text); // c2pstr
  1739.     DebugStr( text );
  1740. #endif
  1741.  
  1742.     //    update the amount of data actually transferred
  1743.     clientParam->ioActCount += pb->usbActCount;
  1744.     USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion - bytes written  " , (UInt32)pb->usbActCount);
  1745.  
  1746.     switch( pb->usbStatus )
  1747.     {
  1748.         //
  1749.         //    only retry low level hardware problems
  1750.         //        note: abort transactions will end up here as well
  1751.         //
  1752.     case kUSBLinkErr:
  1753.     case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  1754.     case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  1755.     case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  1756.     case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  1757.     case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  1758.     case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  1759.         if (  --(pPrinterPB->writeRetryCount) >= 0 ) // = is there so we don't retry clearendpoints forever
  1760.         {
  1761.             if(pPrinterPB->writeStatus == noErr)
  1762.             {
  1763.                 pPrinterPB->writeStatus = pb->usbStatus;
  1764.             }
  1765.             // we got an error, and we still want to retry, clear any stalls
  1766.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion retry" , pb->usbStatus );
  1767.             USBClearPipeStallByReference(pPrinterPB->writePipeRef);
  1768.             pb->usbStatus = noErr;
  1769.             
  1770.             USBExpertStatusLevel(3, pb->usbReference, kPStrPrinterDriverName"**** WriteCompletion clearing endpoint halt *****" , pb->usbStatus );
  1771.             ClearEndpointHalt(pb);    // Sets up PB
  1772.             USBDeviceRequest(pb);
  1773.             return;
  1774.             
  1775.         }
  1776.         break;
  1777.     case kUSBAbortedError:                        /* user cancel, or hot unplug */
  1778.         USBClearPipeStallByReference(pPrinterPB->writePipeRef);
  1779.         USBClearPipeStallByReference(pPrinterPB->deviceRef);
  1780.         break;
  1781.         //
  1782.         //    any other error will be reported to the client
  1783.         //
  1784.     default:
  1785.     case noErr:
  1786.         break;
  1787.     }
  1788.  
  1789.     if ( (pPrinterPB->writeRetryCount > 0) && 
  1790.          (pb->usbStatus == noErr) &&
  1791.          (clientParam->ioActCount < clientParam->ioReqCount) )
  1792.     {
  1793.         //
  1794.         //    haven't finish the client's request
  1795.         //        update the pointers and start another bulkOut transaction
  1796.         //
  1797. #if LOCK_MEMORY
  1798.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1799.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion UnlockMem failed" ) );
  1800. #endif
  1801.         pb->usbBuffer = clientParam->ioBuffer + clientParam->ioActCount;
  1802.         pb->usbReqCount = clientParam->ioReqCount - clientParam->ioActCount;
  1803. #if MAX_USB_TRANSFER_SIZE
  1804.         if ( pb->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1805.             pb->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1806. #endif
  1807. #if DOUBLE_BUFFER
  1808.         //
  1809.         //    make sure we have enough room in our buffer
  1810.         //    then copy the user data into our page aligned buffer
  1811.         //
  1812.         if ( pb->usbReqCount > pPrinterPB->pageWriteAlignedBufferSize )
  1813.             pb->usbReqCount = pPrinterPB->pageWriteAlignedBufferSize;
  1814.             
  1815.         BlockCopy( pb->usbBuffer, pPrinterPB->pageWriteAlignedBuffer, pb->usbReqCount );
  1816.         pb->usbBuffer = pPrinterPB->pageWriteAlignedBuffer;
  1817.         
  1818. #endif
  1819.  
  1820.  
  1821.         pPrinterPB->writeStatus = noErr;
  1822. #if LOCK_MEMORY
  1823.         err = LockMemory( pb->usbBuffer, pb->usbReqCount );
  1824.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion LockMem failed" ) );
  1825.         if ( err == noErr )
  1826. #endif
  1827.             err = SafeUSBBulkWrite( pb );    // Note this is probably hanging off the if above.
  1828.         if ( immediateError(err) )
  1829.         {
  1830.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion finish immed err" , err );
  1831.  
  1832.             pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1833.             if ( pPrinterPB->writeDrvr.ctl != NULL )
  1834.             {
  1835.                 ctlLocal = pPrinterPB->writeDrvr.ctl;
  1836.                 pPrinterPB->writeDrvr.ctl = NULL;
  1837.                 CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, err, clientParam, ctlLocal ); 
  1838.             }
  1839.         }
  1840.     }
  1841.     else
  1842.     {
  1843.         if(pPrinterPB->writeStatus != noErr)
  1844.         {
  1845.             pb->usbStatus = pPrinterPB->writeStatus;
  1846.         }
  1847.         //
  1848.         //        either we have an error which we're not retrying
  1849.         //            or we successfully completed
  1850.         //
  1851. #if LOCK_MEMORY
  1852.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1853.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion concluded UnlockMem failed" ) );
  1854. #endif
  1855.  
  1856.         IF_DEBUG( if (pb->usbStatus != noErr) USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion Error" , pb->usbStatus ) );
  1857.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1858.  
  1859.  
  1860.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"writeDrvr.ctl = " , (UInt32)pPrinterPB->writeDrvr.ctl );
  1861.         if ( pPrinterPB->writeDrvr.ctl != NULL )
  1862.         {
  1863.             ctlLocal = pPrinterPB->writeDrvr.ctl;
  1864.             pPrinterPB->writeDrvr.ctl = NULL;
  1865.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, ctlLocal ); 
  1866.         }
  1867.         else
  1868.         {
  1869.             IF_DEBUG( DebugStr( kPStrPrinterDriverName"WriteCompletion() pPrinterPB->writeDrvr.ctl == NULL" ) );
  1870.         }
  1871.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB PRint, write completion do suspend resume" , pb->usbReference );
  1872.         USBPrintDoSuspendResume(pPrinterPB->interfaceRef);
  1873.     }
  1874. }
  1875.  
  1876. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1877.     Name:        QueueRead
  1878.  
  1879.     Input Parameters:    
  1880.         pb                        MacOS device manager parameter block
  1881.         ctl                    device manager dCtl block
  1882.         pPrinterPB            current printing device class's storage
  1883.         
  1884.     Output Parameters:
  1885.         <none>
  1886.  
  1887.     Description:
  1888.         MacOS DRVR read requests are re-queued here to the USB
  1889.         Since we only allow one read request pending at a time, we're able
  1890.         to use the USB refCon to point to our class driver's storage.
  1891.  
  1892.  
  1893.  
  1894.  
  1895. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1896. void
  1897. QueueRead( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  1898. {    
  1899.     OSStatus    err;
  1900.     USBPB        *usbprint = &pPrinterPB->in;
  1901.     
  1902. #if MACSBUG_ON_READ
  1903.     Str255    text;
  1904.  
  1905.     sprintf( (char *)text, " PrinterClass Read: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  1906.     text[0] = CStrLen((char *)text); // c2pstr
  1907.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  1908.     DebugStr( text );
  1909. #endif
  1910.  
  1911.     // BT - 15Jun99, if we're not currently awake, delay this until we are.
  1912.     if(currentlyAre == kUSBPrintSuspended)
  1913.     {
  1914.         pb->ioResult = ioInProgress;
  1915.         USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, delaying read for resume", 0 );
  1916.         RpPrinterPB = pPrinterPB;
  1917.         Rctl = ctl;
  1918.         Rpb = pb;
  1919.         if( (currentlyAre != kUSBPrintSuspended) && (Rpb != nil) )
  1920.         {
  1921.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, resumed while we wern't looking", 0 );
  1922.             // resumed and executed this while we were doing this.
  1923.             return;
  1924.         }
  1925.         else
  1926.         {
  1927.             // now wait for resume to happen
  1928.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, let resume take over", 0 );
  1929.             return;
  1930.         }        
  1931.     }
  1932.  
  1933.  
  1934.     pb->ioActCount = 0;        // nothing transfered yet
  1935.     if ( pPrinterPB->terminating )
  1936.         pb->ioResult = abortErr;
  1937.     else
  1938.     {
  1939.  
  1940.         pPrinterPB->readRetryCount = 5;
  1941.         pPrinterPB->readStatus = noErr;
  1942.         pPrinterPB->readDrvr.pb= pb;
  1943.         pPrinterPB->readDrvr.ctl = ctl;
  1944.         if (( pPrinterPB->readPipeRef != NULL ) && (pPrinterPB->printerConfigured))
  1945.         {
  1946.             SetNullUSBParamBlock( pPrinterPB->readPipeRef,  usbprint );
  1947.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Set up to do bulk read", pb->ioReqCount );
  1948.             usbprint->usbActCount = 0;
  1949.             usbprint->usbBuffer = pb->ioBuffer;
  1950.             usbprint->usbReqCount = pb->ioReqCount;
  1951.  
  1952. #if MAX_USB_TRANSFER_SIZE
  1953.             //
  1954.             //    the completion routine will queue another BulkWrite until we exhaust the data
  1955.             //        or there is an error which can't be retried
  1956.             //
  1957.             if ( usbprint->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1958.                 usbprint->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1959. #endif
  1960. #if DOUBLE_BUFFER
  1961.             //
  1962.             //    make sure we have enough room in our buffer
  1963.             //    then copy the user data into our page aligned buffer
  1964.             //
  1965.             if ( usbprint->usbReqCount > pPrinterPB->pageReadAlignedBufferSize )
  1966.                 usbprint->usbReqCount = pPrinterPB->pageReadAlignedBufferSize;
  1967.             usbprint->usbBuffer = pPrinterPB->pageReadAlignedBuffer;
  1968. #endif
  1969.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  1970.             usbprint->usbCompletion = (USBCompletion) ReadCompletion;
  1971.             
  1972.             pb->ioResult = ioInProgress;
  1973. #if LOCK_MEMORY
  1974.             err = LockMemory( usbprint->usbBuffer, usbprint->usbReqCount );
  1975.             IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"QueueRead LockMem failed" ) );
  1976.             if ( err == noErr )
  1977. #endif
  1978.             err = SafeUSBBulkRead( usbprint );
  1979.             if ( immediateError(err) )
  1980.             {
  1981.                 USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Error doing bulk read",err );
  1982.                 IF_DEBUG( DebugStr( USBStatusStr(err, kPString) ) );
  1983.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1984.                 pb->ioResult = err;
  1985.             }
  1986.         }
  1987.         else
  1988.         {
  1989.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Read to unopened pipe" , usbprint->usbStatus ) ;
  1990.             pb->ioResult = abortErr;
  1991.         }
  1992.     }
  1993. }
  1994.  
  1995. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1996.     Name:        QueueWrite
  1997.  
  1998.     Input Parameters:    
  1999.         pb                        MacOS device manager parameter block
  2000.         ctl                    device manager dCtl block
  2001.         pPrinterPB            current printing device class's storage
  2002.         
  2003.     Output Parameters:
  2004.         <none>
  2005.  
  2006.     Description:
  2007.         MacOS DRVR write requests are re-queued here to the USB
  2008.         Since we only allow one read request pending at a time, we're able
  2009.         to use the USB refCon to point to our class driver's storage.
  2010.  
  2011.  
  2012.  
  2013. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2014. void
  2015. QueueWrite( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  2016. {
  2017.     OSStatus    err;
  2018.     USBPB        *usbprint = &pPrinterPB->out;
  2019. #if VIRTUAL_MEMORY_CHECK
  2020.     //
  2021.     //    dump the VM table
  2022.     //
  2023.     Str255                        text;
  2024.     LogicalToPhysicalTable        *vmTable;
  2025.     MemoryBlock                    *physical;
  2026.     unsigned long                vmCount,
  2027.                                 vmEntry,
  2028.                                 vmTblLength;
  2029. #endif
  2030.  
  2031. #if MACSBUG_ON_WRITE
  2032.     Str255    text;
  2033.     sprintf( (char *)text, " "kCStrPrinterDriverName"%d @ %08x", pb->ioReqCount, pb->ioBuffer );
  2034.     text[0] = CStrLen((char *)text); // c2pstr
  2035.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2036.     DebugStr( text );
  2037. #endif
  2038.  
  2039.     // BT - 15Jun99, if we're not currently awake, delay this until we are.
  2040.     if(currentlyAre == kUSBPrintSuspended)
  2041.     {
  2042.         pb->ioResult = ioInProgress;
  2043.         USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, delaying write for resume", 0 );
  2044.  
  2045.         WpPrinterPB = pPrinterPB;
  2046.         Wctl = ctl;
  2047.         Wpb = pb;
  2048.         if( (currentlyAre != kUSBPrintSuspended) && (Wpb != nil) )
  2049.         {
  2050.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, resumed while we wern't looking", 0 );
  2051.             // resumed and executed this while we were doing this.
  2052.         }
  2053.         else
  2054.         {
  2055.             // now wait for resume to happen
  2056.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, let resume take over", 0 );
  2057.             return;
  2058.         }        
  2059.     }
  2060.  
  2061.  
  2062.  
  2063. #if VIRTUAL_MEMORY_CHECK
  2064.     //
  2065.     //    this check current won't compile without runtime error: need to lock memory, but lock has moved
  2066.     //
  2067.     sprintf( (char *)text, " "kCStrPrinterDriverName"Write: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  2068.     text[0] = CStrLen((char *)text); // c2pstr
  2069.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2070.     
  2071.     vmCount = 127;
  2072.     vmTblLength = (vmCount+1)*sizeof(MemoryBlock);
  2073.     vmTable = (LogicalToPhysicalTable *) NewPtrSys( vmTblLength );
  2074.     LockMemory( vmTable, vmTblLength );
  2075.     LockMemory( &vmCount, sizeof(unsigned long) );
  2076.     vmTable->logical.address = pb->ioBuffer;
  2077.     vmTable->logical.count = pb->ioReqCount;
  2078.     err = GetPhysical( vmTable, &vmCount );
  2079.     
  2080.     if ( err == noErr )
  2081.     {
  2082.         for ( vmEntry = 0, physical = &vmTable->physical[0]; vmEntry < vmCount; ++vmEntry , ++physical)
  2083.         {
  2084.             sprintf( (char *)text, " "kCStrPrinterDriverName"Write: VM @%08x (%d)", physical->address, physical->count );
  2085.             text[0] = CStrLen((char *)text); // c2pstr
  2086.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2087.         }
  2088.     }
  2089.     UnlockMemory( vmTable, vmTblLength );
  2090.     UnlockMemory( &vmCount, sizeof(unsigned long) );
  2091. #endif
  2092.     pb->ioActCount = 0;        // nothing transfered yet
  2093.  
  2094.  
  2095.     usbprint->usbStatus = noErr;    // forget about abort and things from previous writes
  2096.     if ( pPrinterPB->terminating )
  2097.         pb->ioResult = abortErr;
  2098.     else
  2099.     {
  2100.         pPrinterPB->writeRetryCount = 5;
  2101.         pPrinterPB->writeStatus = noErr;
  2102.         pPrinterPB->writeDrvr.pb = pb;
  2103.         pPrinterPB->writeDrvr.ctl = ctl;
  2104.         if (( pPrinterPB->writePipeRef != NULL ) && (pPrinterPB->printerConfigured))
  2105.         {
  2106.             SetNullUSBParamBlock( pPrinterPB->writePipeRef,  usbprint );
  2107.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Set up to do bulk write", pb->ioReqCount );
  2108.             usbprint->usbActCount = 0;
  2109.             usbprint->usbBuffer = pb->ioBuffer;
  2110.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  2111.             usbprint->usbCompletion = (USBCompletion) WriteCompletion;
  2112.             
  2113. #if MAX_USB_TRANSFER_SIZE
  2114.             //
  2115.             //    the completion routine will queue another BulkWrite until we exhaust the data
  2116.             //        or there is an error which can't be retried
  2117.             //
  2118.             if ( pb->ioReqCount > MAX_USB_TRANSFER_SIZE )
  2119.                 usbprint->usbReqCount = MAX_USB_TRANSFER_SIZE;
  2120.             else
  2121. #endif
  2122.                 usbprint->usbReqCount = pb->ioReqCount;
  2123.     
  2124.  
  2125. #if DOUBLE_BUFFER
  2126.             //
  2127.             //    make sure we have enough room in our buffer
  2128.             //    then copy the user data into our page aligned buffer
  2129.             //
  2130.             if ( usbprint->usbReqCount > pPrinterPB->pageWriteAlignedBufferSize )
  2131.                 usbprint->usbReqCount = pPrinterPB->pageWriteAlignedBufferSize;
  2132.             BlockCopy( usbprint->usbBuffer, pPrinterPB->pageWriteAlignedBuffer, usbprint->usbReqCount );
  2133.             usbprint->usbBuffer = pPrinterPB->pageWriteAlignedBuffer;
  2134. #endif
  2135.             pb->ioResult = ioInProgress;
  2136.     
  2137. #if LOCK_MEMORY
  2138.             err = LockMemory( usbprint->usbBuffer, usbprint->usbReqCount );
  2139.             IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"QueueWrite LockMem failed" ) );
  2140.             if ( err == noErr )
  2141. #endif
  2142.                 err = SafeUSBBulkWrite( usbprint );
  2143.             if ( immediateError(err) )
  2144.             {
  2145.                 USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Immediate error doing bulk write",0 );
  2146.                 IF_DEBUG( DebugStr( USBStatusStr(err, kPString) ) );
  2147.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2148.                 pb->ioResult = err;
  2149.             }
  2150.             //
  2151.             //    note our logging is one write for each the client request
  2152.             //        not one write for each usb transaction
  2153.             //
  2154.             LOGGING( fwrite( pb->ioBuffer, sizeof(char), pb->ioReqCount, logfile ) );
  2155.         }
  2156.         else
  2157.         {
  2158.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Write to unopened pipe" , usbprint->usbStatus );
  2159.             pb->ioResult = abortErr;
  2160.         }
  2161.     }
  2162. }
  2163.  
  2164.  
  2165. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2166.     Name:        Abort
  2167.  
  2168.     Input Parameters:    
  2169.         refNum            DRVR refnum
  2170.         pPrinterPB        current printing device class's storage
  2171.  
  2172.     Output Parameters:
  2173.         
  2174.     Description:
  2175.         Asynchronous completion.
  2176.         Note: USBAbortPipeByReference can leave the data toggle in the wrong state.
  2177.                 We need to abort both pipes, and then the client must soft reset the printer
  2178.                 to get the printer's data toggles correct.
  2179.         We prematurely call completion routines for active i/o so that CloseDriverSync
  2180.             will not hang the system after an abort, including hot unplug. This works out okay,
  2181.             since the request will be dequeued now, and when the i/o actually terminates
  2182.             the system will be called with an invalid queue element and then reject this second
  2183.             attempt to dequeue the i/o.
  2184.  
  2185.  
  2186.  
  2187.  
  2188. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2189. OSStatus
  2190. Abort( DriverRefNum refNum, struct usbPrinterPBStruct *pPrinterPB )
  2191. {
  2192.     OSStatus        err = noErr;
  2193.  
  2194.     //
  2195.     //    if there's any pending io this will call the completion routine
  2196.     //
  2197.     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called" , 0);
  2198.     if (refNum == pPrinterPB->outRefNum)
  2199.     {
  2200.         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called on out pipe" , 0);
  2201.         if ( pPrinterPB->in.usbCompletion != (USBCompletion) NULL )
  2202.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "***** Abort with write in progress" , 0);
  2203.         
  2204.         err = USBAbortPipeByReference( pPrinterPB->writePipeRef );
  2205.         err = USBClearPipeStallByReference( pPrinterPB->writePipeRef );
  2206.         
  2207.         if ( pPrinterPB->out.usbCompletion != (USBCompletion) NULL )
  2208.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, abortErr, pPrinterPB->writeDrvr.pb, pPrinterPB->writeDrvr.ctl ); 
  2209.     }
  2210.     
  2211.     if (refNum == pPrinterPB->inRefNum)
  2212.     {
  2213.         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called on in pipe" , 0);
  2214.         if ( pPrinterPB->out.usbCompletion != (USBCompletion) NULL )
  2215.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "***** Abort with read in progress" , 0);
  2216.  
  2217.         err = USBAbortPipeByReference( pPrinterPB->readPipeRef );
  2218.         err = USBClearPipeStallByReference( pPrinterPB->readPipeRef );
  2219.  
  2220.         if ( pPrinterPB->in.usbCompletion != (USBCompletion) NULL )
  2221.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, abortErr, pPrinterPB->readDrvr.pb, pPrinterPB->readDrvr.ctl ); 
  2222.     }
  2223.     return err;
  2224. }
  2225.  
  2226.  
  2227. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2228.     Name:        CompletionProc
  2229.  
  2230.     Input Parameters:    
  2231.         pb                    USB param block ptr
  2232.     
  2233.     Output Parameters:
  2234.         
  2235.     Description:
  2236.         Asynchronous completion routine for DRVR requests.
  2237.  
  2238.  
  2239.  
  2240.  
  2241.  
  2242. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2243. static void 
  2244. CompletionProc(USBPB *pb)
  2245. {
  2246.     //    call the user completion routine
  2247.     struct usbPrinterPBStruct
  2248.                     *pPrinterPB = (struct usbPrinterPBStruct    *) pb->usbRefcon;
  2249.     IOParamPtr     clientParam = pPrinterPB->statusDrvr.pb;
  2250.  
  2251.     clientParam->ioActCount = pb->usbActCount;
  2252.  
  2253.     if ( pb->usbStatus != noErr ) 
  2254.     {
  2255.         USBClearPipeStallByReference(pb->usbReference);  // we got an error, try to clear any stalls
  2256.  
  2257.         IF_DEBUG( USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "CompletionProc Error" , pb->usbStatus ) );
  2258.         IF_DEBUG( USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, USBStatusStr(pb->usbStatus, kPString) , pb->usbStatus ) );
  2259.     }
  2260.  
  2261.     pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2262.     if ( pPrinterPB->statusDrvr.ctl != NULL )
  2263.         CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, pPrinterPB->statusDrvr.ctl ); 
  2264. }
  2265.  
  2266. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2267.     Name:        CentronicsStatus
  2268.  
  2269.     Input Parameters:    
  2270.         pb                        MacOS device manager parameter block
  2271.         ctl                    device manager dCtl block
  2272.         pPrinterPB            current printing device class's storage
  2273.  
  2274.     Output Parameters:
  2275.         pStatusByte        
  2276.         
  2277.     Description:
  2278.         setup the device request for a USB printer class request one byte status.
  2279.  
  2280.  
  2281.  
  2282.  
  2283.  
  2284. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2285. static void
  2286. CentronicsStatus( USBPB *usbprint, Ptr buffer, short interfaceNumber )
  2287. {
  2288.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  2289.  
  2290.     usbprint->usb.cntl.BRequest = kUSBPrintClassGetCentronicsStatus;
  2291.     usbprint->usb.cntl.WValue = 0;
  2292.     usbprint->usb.cntl.WIndex = interfaceNumber;
  2293.  
  2294.     usbprint->usbReqCount = 1;
  2295.     usbprint->usbBuffer = buffer;
  2296. }
  2297.  
  2298. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2299.     Name:        ClearEndpointHalt
  2300.  
  2301.     Input Parameters:    
  2302.         usbprint                USB param block
  2303.  
  2304.     Output Parameters:
  2305.         
  2306.     Description:
  2307.         Setup the device request for a USB clear endpoint halt.
  2308.  
  2309. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2310. void
  2311. ClearEndpointHalt( USBPB *usbprint)
  2312. {
  2313.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBStandard, kUSBEndpoint);
  2314.  
  2315.     usbprint->usb.cntl.BRequest = kUSBRqClearFeature;
  2316.     usbprint->usb.cntl.WValue = kUSBFeatureEndpointStall;
  2317.     usbprint->usbFlags = kUSBAddressRequest;
  2318.  
  2319.     usbprint->usbReqCount = 0;
  2320.     usbprint->usbBuffer = NULL;
  2321.     
  2322.  
  2323. }
  2324.  
  2325. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2326.     Name:        SoftReset
  2327.  
  2328.     Input Parameters:    
  2329.         usbprint                USB param block
  2330.         interfaceNumber
  2331.  
  2332.     Output Parameters:
  2333.         
  2334.     Description:
  2335.         Setup the device request for a USB printer class request soft reset.
  2336.  
  2337.  
  2338.  
  2339.  
  2340.  
  2341. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2342. void
  2343. SoftReset( USBPB *usbprint, short interfaceNumber )
  2344. {
  2345.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBClass, kUSBOther);
  2346.  
  2347.     usbprint->usb.cntl.BRequest = kUSBPrintClassSoftReset;
  2348.     usbprint->usb.cntl.WValue = 0;
  2349.     usbprint->usb.cntl.WIndex = interfaceNumber;
  2350.  
  2351.     usbprint->usbReqCount = 0;
  2352.     usbprint->usbBuffer = NULL;
  2353.     
  2354.  
  2355. }
  2356.  
  2357. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2358.     Name:        CapabilityRequest
  2359.  
  2360.     Input Parameters:    
  2361.         usbprint            USB parameter block
  2362.         p                    result pointer
  2363.         length            amount of data allocated
  2364.         config
  2365.         interfaceNum
  2366.         alternateSetting
  2367.         
  2368.  
  2369.     Output Parameters:
  2370.         p                    result pointer
  2371.         length            amount of data allocated
  2372.         
  2373.     Description:
  2374.         setup the device request for a USB printer class request 1284 id string.
  2375.  
  2376.  
  2377.  
  2378.  
  2379.  
  2380. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2381. void
  2382. CapabilityRequest( USBPB *pb, Ptr p, long length, short configValue, short interfaceNumber, short alternateSetting  )
  2383. {
  2384.  
  2385.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  2386.  
  2387.     pb->usb.cntl.BRequest = kUSBPrintClassGetDeviceID;
  2388.     pb->usb.cntl.WValue = configValue;        // configuration
  2389.     pb->usb.cntl.WIndex = (interfaceNumber<<8) | alternateSetting;
  2390.  
  2391.     pb->usbReqCount = length;
  2392.     pb->usbBuffer = p;
  2393.  
  2394. }
  2395.  
  2396. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2397.     Name:        StatusControlRequests
  2398.  
  2399.     Input Parameters:    
  2400.         pb                        MacOS device manager parameter block
  2401.         ctl                    device manager dCtl block
  2402.         pPrinterPB            current printing device class's storage
  2403.  
  2404.     Output Parameters:
  2405.         
  2406.     Description:
  2407.         Asynchronous completion.
  2408.  
  2409.  
  2410.  
  2411.  
  2412. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2413.  
  2414. void
  2415. ControlStatusRequests( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  2416. {
  2417.  
  2418.     //
  2419.     //    queue a transaction to retrieve the centronics status
  2420.     //
  2421.     OSStatus    err;
  2422.     USBPB        *usbprint = &pPrinterPB->pb;
  2423.     Boolean        dosomething = false;
  2424.     
  2425. #if DEBUG
  2426.     Str255        text;
  2427.  
  2428.     sprintf( (char *)text, " PrinterClass ControlStatus: %d", ((CntrlParam *) pb)->csCode );
  2429.     text[0] = CStrLen((char *)text); // c2pstr
  2430.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2431. #endif
  2432.  
  2433.  
  2434.  
  2435.     if (pPrinterPB->terminating)
  2436.     {
  2437.         pb->ioResult = abortErr;
  2438.     }
  2439.     else
  2440.     {
  2441.         switch( ((CntrlParam *) pb)->csCode )
  2442.         {
  2443.         case kDrvrCentronicsStatus:
  2444.             dosomething = true;
  2445.             CentronicsStatus( usbprint,  *((Ptr *)((CntrlParam *) pb)->csParam), pPrinterPB->interfaceNumber );
  2446.             SetNullUSBParamBlock(pPrinterPB->deviceRef,  usbprint );
  2447.             break;
  2448.             
  2449.             
  2450.         case kDrvr1284IdString:
  2451.             dosomething = true;
  2452.             CapabilityRequest( usbprint,
  2453.                                     *((Ptr *)((CntrlParam *) pb)->csParam),
  2454.                                     *((long *) &((CntrlParam *) pb)->csParam[4]),
  2455.                                     0,        // configuration
  2456.                                     pPrinterPB->interfaceNumber,
  2457.                                     pPrinterPB->alternateSetting);
  2458.             SetNullUSBParamBlock(pPrinterPB->deviceRef,  usbprint );
  2459.             break;
  2460.             
  2461.         case kDrvrSoftReset:
  2462.             dosomething = true;
  2463.             if ( ((CntrlParam *) pb)->ioCRefNum == pPrinterPB->outRefNum )
  2464.             {
  2465.                 SetNullUSBParamBlock(pPrinterPB->writePipeRef,  usbprint );
  2466.             }
  2467.             else 
  2468.             {
  2469.                 SetNullUSBParamBlock(pPrinterPB->readPipeRef,  usbprint );
  2470.             }
  2471.             ClearEndpointHalt( usbprint );
  2472.             break;
  2473.         
  2474.         case kDrvrPrivateLog:
  2475.             // BT - 15Jun99, print a message in the log for the 68k code.
  2476.             USBExpertStatusLevel(((CntrlParam *) pb)->csParam[2], pPrinterPB->deviceRef, *(unsigned char **)(((CntrlParam *) pb)->csParam), *((long *)&((CntrlParam *) pb)->csParam[4]) );
  2477.             return;
  2478.             break;
  2479.         
  2480.         case kDrvrPrivateOpnClose:
  2481.             // BT - 15Jun99, Open or close has been called, arrange for suspend or resume.
  2482.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB print driver kDrvrPrivateOpnClose", ((CntrlParam *) pb)->csParam[0] == 0);
  2483.             // If csParam[0] is 1 we're being opened, if 0 we're being closed
  2484.             if(((CntrlParam *) pb)->csParam[0] == 1)
  2485.             {
  2486.                 openRef++;
  2487.                 wantToBe = kUSBPrintResumed;
  2488.                 // We're being opened
  2489.             }
  2490.             else if(((CntrlParam *) pb)->csParam[0] == 0)
  2491.             {
  2492.                 if (--openRef < 0) 
  2493.                     openRef = 0;
  2494.                 
  2495.                 if (!openRef)  // is this the last close?
  2496.                     wantToBe = kUSBPrintSuspended;
  2497.                 else
  2498.                     wantToBe = kUSBPrintResumed;
  2499.             }
  2500.             else
  2501.             {
  2502.                 USBExpertStatusLevel(2, pPrinterPB->deviceRef, "\pUSB print driver kDrvrPrivateOpnClose unknown message", ((CntrlParam *) pb)->csParam[0] == 0);
  2503.             }
  2504.             USBPrintDoSuspendResume(pPrinterPB->interfaceRef);
  2505.             return;
  2506.             break;
  2507.         default:
  2508.             break;
  2509.         }
  2510.     
  2511.         if ( !dosomething )
  2512.             pb->ioResult = paramErr;
  2513.         else
  2514.         {
  2515.             // BT - 15Jun99, if we're not currently awake, delay this until we are.
  2516.             if(currentlyAre == kUSBPrintSuspended )
  2517.             {
  2518.                 
  2519.                 if (Cpb != nil){
  2520.                     pb->ioResult = notOpenErr;
  2521.                     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, Can't support more than one delayed control call while suspended!", pb->ioResult );
  2522.                     return;
  2523.                 }
  2524.                     
  2525.                 pb->ioResult = ioInProgress;
  2526.                 USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, delaying control for resume", 0 );
  2527.                 CpPrinterPB = pPrinterPB;
  2528.                 Cctl = ctl;
  2529.                 Cpb = pb;
  2530.                 if( (currentlyAre != kUSBPrintSuspended) && (Rpb != nil) )
  2531.                 {
  2532.                     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, resumed while we wern't looking", 0 );
  2533.                     // resumed and executed this while we were doing this.
  2534.                     return;
  2535.                 }
  2536.                 else
  2537.                 {
  2538.                     // now wait for resume to happen
  2539.                     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, let resume take over", 0 );
  2540.                     return;
  2541.                 }        
  2542.             }
  2543.  
  2544.             usbprint->usbActCount = 0;
  2545.             usbprint->usbCompletion = (USBCompletion)CompletionProc;
  2546.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  2547.         
  2548.             pb->ioResult = ioInProgress;
  2549.             pPrinterPB->statusDrvr.pb = pb;
  2550.             pPrinterPB->statusDrvr.ctl = ctl;
  2551.         
  2552.             err = USBDeviceRequest(usbprint);
  2553.             if(immediateError(err))
  2554.             {
  2555.                 USBExpertFatalError(usbprint->usbReference, err, kPStrPrinterDriverName"StatusControlRequests", 0);
  2556.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2557.                 pb->ioResult = err;
  2558.             }
  2559.         }
  2560.     }
  2561. }
  2562.  
  2563.  
  2564. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2565.     Name:        PrinterDeviceCompletionProc
  2566.  
  2567.     Input Parameters:    
  2568.         pb                refCon tells which state we're completing
  2569.  
  2570.     Output Parameters:
  2571.         <none>
  2572.         
  2573.     Description:
  2574.         Complete asynch transactions initiated by PrinterDeviceInitiateTransaction.
  2575.  
  2576.  
  2577.  
  2578.  
  2579.  
  2580.  
  2581.  
  2582.  
  2583.  
  2584.  
  2585. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2586.  
  2587. static void 
  2588. PrinterDeviceCompletionProc(USBPB *pb)
  2589. {
  2590. Str255        tempstr1,tempstr2;
  2591. register     struct usbPrinterPBStruct *pPrinterPB;
  2592. OSStatus    err;
  2593. UInt32        i = 0;
  2594.     
  2595.     
  2596.     pPrinterPB = (struct usbPrinterPBStruct *)(pb);
  2597.  
  2598.     pPrinterPB->transDepth--; 
  2599.     if ((pPrinterPB->transDepth < 0) || (pPrinterPB->transDepth > 1))
  2600.     {
  2601.         USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName "CompletionProc Illegal Transaction Depth", pPrinterPB->transDepth );
  2602.     }
  2603.  
  2604.     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, StateStr(pPrinterPB->pb.usbRefcon, kPString) , pPrinterPB->pb.usbStatus );
  2605.  
  2606.     pPrinterPB->delayInProgress = false;
  2607.     
  2608.     if ( pPrinterPB->terminating )
  2609.     {
  2610.         //    if we've been hot unplugged
  2611.         //        don't startup any new transactions
  2612.         //     allow PrintDriverFinalize to continue
  2613.         pPrinterPB->pb.usbStatus = kUSBAbortedError;
  2614.         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2615.     }
  2616.     
  2617.  
  2618.     switch( pPrinterPB->pb.usbStatus )
  2619.     {
  2620.         case kUSBPending:
  2621.         case noErr:
  2622.             pPrinterPB->pb.usbRefcon &= ~kRetryTransaction;
  2623.             pPrinterPB->retryCount = kPrinterRetryCount;
  2624.             break;
  2625.             
  2626.         case kUSBLinkErr:
  2627.         case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  2628.         case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  2629.         case kUSBDataToggleErr:                            /*  Pipe stall, Bad data toggle */
  2630.         case kUSBNotRespondingErr:                        /*  Pipe stall, No device, device hung */
  2631.         case kUSBPIDCheckErr:                            /*  Pipe stall, PID CRC error */
  2632.         case kUSBWrongPIDErr:                            /*  Pipe stall, Bad or wrong PID */
  2633.         case kUSBTimedOut:                                /* Transaction timed out. */
  2634.         default:
  2635.         
  2636.             USBClearPipeStallByReference(pPrinterPB->deviceRef);  // we got an error, try to clear any stalls
  2637.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "    retry", pPrinterPB->pb.usbStatus);
  2638.             
  2639.             // clear out the transaction pending flag
  2640.             pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2641.             pPrinterPB->pb.usbRefcon |= kRetryTransaction;
  2642.             pPrinterPB->retryCount--;
  2643.             if (!pPrinterPB->retryCount)
  2644.             {
  2645.                 USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName "Retry failed", pPrinterPB->pb.usbRefcon & ~kRetryTransaction);
  2646.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2647.             } 
  2648.             else 
  2649.             {
  2650.                 pPrinterPB->pb.usbStatus = noErr;             // let's retry one more time
  2651.             }
  2652.             break;
  2653.             
  2654.         case kUSBNotFound:
  2655.             break;
  2656.             
  2657.         case kUSBAbortedError:                        /* user cancel, or hot unplug */
  2658.             // clear out the transaction pending flag
  2659.             pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;
  2660.             pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2661.             pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2662.             break;
  2663.     }
  2664.  
  2665.     if (pPrinterPB->pb.usbRefcon & kTransactionPending)             
  2666.     {            
  2667.         short    length;
  2668.     
  2669.         //
  2670.         //    advance to the next state
  2671.         //
  2672.         pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2673.         switch(pPrinterPB->pb.usbRefcon)
  2674.         {
  2675.             case kFindInterface_bidirectional:
  2676.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_bidirectional completed", pPrinterPB->pb.usb.cntl.WIndex);
  2677.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2678.                 {
  2679.                     if ((pPrinterPB->pb.usbClassType == kUSBPrintingClass) && 
  2680.                         (pPrinterPB->pb.usbSubclass == kUSBPrinterSubclass) &&
  2681.                         (pPrinterPB->pb.usbProtocol == kUSBPrinterBidirectionalProtocol))
  2682.                     {
  2683.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Found bidirectional interface at alt setting ", pPrinterPB->pb.usbOther);
  2684.                         pPrinterPB->configurationNumber = pPrinterPB->pb.usb.cntl.WValue;
  2685.                         pPrinterPB->alternateSetting = pPrinterPB->pb.usbOther;
  2686.                         pPrinterPB->printerProtocol = kUSBPrinterBidirectionalProtocol;
  2687.                         
  2688.                         // if we started out as a device class driver, then the interface descriptor will be NULL
  2689.                         // this would mean that the device will need to be opened before anything can be done with it
  2690.                         // if the interface descriptor point isn't null, then we started as an interface driver,
  2691.                         // so just skip by the opendevice call
  2692.                         if (pPrinterPB->pInterfaceDescriptor != NULL)
  2693.                         {
  2694.                         // did we find the interface we were looking for?
  2695.                             if (pPrinterPB->interfaceNumber == pPrinterPB->pb.usb.cntl.WIndex)
  2696.                             {
  2697.                                 pPrinterPB->pb.usbRefcon = kSetInterface;
  2698.                             }
  2699.                             else
  2700.                             {
  2701.                                 USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_Bidirectional didn't find the right interface", 0);
  2702.                             }
  2703.                         }
  2704.                         else
  2705.                         {
  2706.                             pPrinterPB->pb.usbRefcon = kOpenDevice;
  2707.                             pPrinterPB->interfaceNumber = pPrinterPB->pb.usb.cntl.WIndex;
  2708.                         }
  2709.                     }
  2710.                 }
  2711.                 else
  2712.                 {
  2713.                     if ( pPrinterPB->pb.usbStatus == kUSBNotFound )
  2714.                     {
  2715.                         USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Bidirectional interface was not found", pPrinterPB->pb.usb.cntl.WIndex);
  2716.                         pPrinterPB->pb.usbRefcon = kFindInterface_unidirectional;
  2717.                         pPrinterPB->pb.usbStatus = noErr;  // must clear error for state machine to continue <USB46>
  2718.                     }
  2719.                     else
  2720.                     {
  2721.                         USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_bidirectional failed", 0);
  2722.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2723.                     }
  2724.                 }
  2725.                 break;
  2726.                 
  2727.             case kFindInterface_unidirectional:
  2728.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_unidirectional completed", pPrinterPB->pb.usb.cntl.WIndex);
  2729.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2730.                 {
  2731.                     if ((pPrinterPB->pb.usbClassType == kUSBPrintingClass) && 
  2732.                         (pPrinterPB->pb.usbSubclass == kUSBPrinterSubclass) &&
  2733.                         (pPrinterPB->pb.usbProtocol == kUSBPrinterUnidirectionalProtocol))
  2734.                     {
  2735.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Found unidirection interface at alt setting ", pPrinterPB->pb.usbOther);
  2736.                         pPrinterPB->pb.usbRefcon = kOpenDevice;
  2737.                         pPrinterPB->configurationNumber = pPrinterPB->pb.usb.cntl.WValue;
  2738.                         pPrinterPB->alternateSetting = pPrinterPB->pb.usbOther;
  2739.                         pPrinterPB->printerProtocol = kUSBPrinterUnidirectionalProtocol;
  2740.                         // if we started out as a device class driver, then the interface descriptor will be NULL
  2741.                         // this would mean that the device will need to be opened before anything can be done with it
  2742.                         // if the interface descriptor point isn't null, then we started as an interface driver,
  2743.                         // so just skip by the opendevice call
  2744.                         if (pPrinterPB->pInterfaceDescriptor)
  2745.                         {
  2746.                             if (pPrinterPB->interfaceNumber == pPrinterPB->pb.usb.cntl.WIndex)
  2747.                             {
  2748.                                 pPrinterPB->pb.usbRefcon = kSetInterface;
  2749.                             }
  2750.                             else
  2751.                             {
  2752.                                 USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_Unidirectional didn't find the right interface", 0);
  2753.                             }
  2754.                         }
  2755.                         else
  2756.                         {
  2757.                             pPrinterPB->pb.usbRefcon = kOpenDevice;
  2758.                             pPrinterPB->interfaceNumber = pPrinterPB->pb.usb.cntl.WIndex;
  2759.                         }
  2760.                     }
  2761.                 }
  2762.                 else
  2763.                 {
  2764.                     if ( pPrinterPB->pb.usbStatus == kUSBNotFound )
  2765.                     {
  2766.                         USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Unidirectional interface was not found", pPrinterPB->pb.usb.cntl.WIndex);
  2767.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2768.                     }
  2769.                     else
  2770.                     {
  2771.                         USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_unidirectional failed", 0);
  2772.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2773.                     }
  2774.                 }
  2775.                 break;
  2776.                 
  2777.             case kOpenDevice:
  2778.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2779.                 {
  2780.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kOpenDevice completed", pPrinterPB->pb.usbStatus);
  2781.                     pPrinterPB->pb.usbRefcon = kNewInterfaceRef;
  2782.                 }
  2783.                 else
  2784.                 {
  2785.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kOpenDevice failed", 0);
  2786.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2787.                 }
  2788.                 break;
  2789.                 
  2790.             case kNewInterfaceRef:
  2791.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kNewInterfaceRef completed", pPrinterPB->pb.usbReference);
  2792.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2793.                 {
  2794.                     pPrinterPB->interfaceRef = pPrinterPB->pb.usbReference;
  2795.                     pPrinterPB->pb.usbRefcon = kSetInterface;
  2796.                 }
  2797.                 else
  2798.                 {
  2799.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kNewInterfaceRef failed", 0);
  2800.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2801.                 }
  2802.                 break;
  2803.             
  2804.             case kSetInterface:
  2805.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kSetInterface completed", 0);
  2806.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2807.                 {
  2808.                     pPrinterPB->pb.usbRefcon = kConfigureInterface;
  2809.                 }
  2810.                 else
  2811.                 {
  2812.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kSetInterface failed", 0);
  2813.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2814.                 }
  2815.                 break;
  2816.             
  2817.             case kConfigureInterface:
  2818.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kConfigureInterface completed, pipes = ", pPrinterPB->pb.usbOther);
  2819.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2820.                 {
  2821.                     pPrinterPB->pipeCount = pPrinterPB->pb.usbOther;
  2822.                     pPrinterPB->pb.usbRefcon = kGetCapabilityString;
  2823.                 }
  2824.                 else
  2825.                 {
  2826.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kConfigureInterface failed", 0);
  2827.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2828.                 }
  2829.                 break;
  2830.             
  2831.             case kGetCapabilityString:
  2832.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCapabilityString completed", pPrinterPB->pb.usbStatus);
  2833.                 
  2834.                 if ( pPrinterPB->pb.usbActCount >= 2 )
  2835.                 {
  2836.                     length = pPrinterPB->pCapabilityString[1] | (pPrinterPB->pCapabilityString[0] << 8);
  2837.                 }
  2838.                 else
  2839.                 {
  2840.                     length = 0;
  2841.                 }
  2842.     
  2843.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2844.                 {
  2845.                     //
  2846.                     //    In the short term (fall '98) several vendors are planning on shipping 
  2847.                     //        devices with a parallel port and using the Lucent USS-720 USB-to-parallel hardware.
  2848.                     //    Unfortunately this isn't an ideal solution from the USB perspective:
  2849.                     //        users can leave the printer off while the cable responds that there's
  2850.                     //        a printer connected. Then we have no way of using the DEVICE_ID
  2851.                     //        string to tag the printer and register it.
  2852.                     //    To alleviate this situation, we repeatedly poll the USS-720 if the DEVICE_ID
  2853.                     //        string is null. Every few seconds we'll retry this state.
  2854.                     //    At some point the user wants to print and switches on the printer. The class
  2855.                     //    driver then picks up from here and registers the device properly.
  2856.                     //
  2857.                     
  2858.                     if ( pPrinterPB->pb.usbActCount == 0 )
  2859.                         pPrinterPB->pb.usbRefcon = kDelayGetCapability;
  2860.                     else
  2861.                         pPrinterPB->pb.usbRefcon = kFindBulkOutPipe;
  2862.                 }
  2863.                 else
  2864.                 {
  2865.                     if ( pPrinterPB->pb.usbStatus == kUSBOverRunErr )
  2866.                     {
  2867.                         //
  2868.                         //    if we've haven't managed to read the whole capability string
  2869.                         //        we need to allocate memory and read it in by initiating kGetFullCapabilityString
  2870.                         //
  2871.     
  2872.                         if ( length > sizeof(pPrinterPB->capability) && pPrinterPB->pb.usbRefcon == kGetCapabilityString )
  2873.                         {
  2874.                             pPrinterPB->pb.usbRefcon = kAllocateCapabilityMem;
  2875.                             pPrinterPB->pb.usbStatus = noErr;  // must clear error for state machine to continue <USB46>
  2876.                             break;                               // advance to that state <USB46>
  2877.                         }    
  2878.                         
  2879.                 
  2880.                     }
  2881.                     else
  2882.                     {
  2883.                         USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetCapabilityString failed", 0);
  2884.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2885.                     }
  2886.                 }
  2887.                 
  2888.                 // write the capability string to the log
  2889.                 if ((pPrinterPB->pb.usbStatus == kUSBOverRunErr)  || (pPrinterPB->pb.usbStatus == noErr))
  2890.                 {
  2891.                     if (length > 2)                     // is there a valid string? (length more than 2 bytes)
  2892.                     {
  2893.                         length -= 2;
  2894.                         if (length > 200)                // cut the string off at 200 characters
  2895.                             length = 200;
  2896.                             
  2897.                         BlockMove( (Ptr)&(pPrinterPB->pCapabilityString[2]), (Ptr)tempstr2, length);
  2898.                         tempstr2[length] = '\0';        // mark the end of the cstring
  2899.                         
  2900.                         sprintf( (char *)tempstr1, (char const *) kCStrPrinterDriverName"1284 Capability String: %s", tempstr2 );
  2901.                         CStrToPStr( (unsigned char *)tempstr2, (char *)tempstr1);    // convert it to a pstring
  2902.                     }
  2903.                     else
  2904.                     {
  2905.                         CStrToPStr( (unsigned char *)tempstr2, (char *) kCStrPrinterDriverName"Capability string is empty!!" );
  2906.                     }
  2907.                     USBExpertStatusLevel(kNormalStatusLevel,  pPrinterPB->deviceRef, tempstr2, length);
  2908.                 }
  2909.                 break;
  2910.                 
  2911.             case kDelayGetCapability:
  2912.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kDelayGetCapability completed", pPrinterPB->pb.usbStatus);
  2913.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2914.                 {
  2915.                     pPrinterPB->pb.usbRefcon = kGetCapabilityString;
  2916.                 }
  2917.                 else
  2918.                 {
  2919.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kDelayGetCapability failed", 0);
  2920.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2921.                 }
  2922.                 break;
  2923.                 
  2924.             case kAllocateCapabilityMem:
  2925.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kAllocateCapabilityMem completed", pPrinterPB->pb.usbStatus);
  2926.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2927.                 {
  2928.                     pPrinterPB->pCapabilityString = pPrinterPB->pb.usbBuffer;
  2929.                     pPrinterPB->pb.usbRefcon = kGetFullCapabilityString;    
  2930.                 }
  2931.                 else
  2932.                 {
  2933.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kAllocateCapabilityMem failed", 0);
  2934.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2935.                 }
  2936.                 break;
  2937.             
  2938.             case kGetFullCapabilityString:
  2939.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetFullCapabilityString completed", pPrinterPB->pb.usbStatus);
  2940.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2941.                 {
  2942.                     pPrinterPB->pb.usbRefcon = kGetInterface;
  2943.                 }
  2944.                 else
  2945.                 {
  2946.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetFullCapabilityString failed", 0);
  2947.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2948.                 }
  2949.                 break;
  2950.                 
  2951.             case kGetInterface:
  2952.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetInterface completed", pPrinterPB->pb.usbStatus);
  2953.                 if (( pPrinterPB->pb.usbStatus == noErr ) && (pPrinterPB->whichAltInterface == pPrinterPB->alternateSetting))
  2954.                 {
  2955.                     pPrinterPB->pb.usbRefcon = kFindBulkOutPipe;
  2956.                 }
  2957.                 else
  2958.                 {
  2959.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetInterface - wrong interface selected", pPrinterPB->whichAltInterface);
  2960.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2961.                 }
  2962.                 break;
  2963.  
  2964.             case kFindBulkOutPipe:
  2965.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkOutPipe completed", pPrinterPB->pb.usbReference);
  2966.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2967.                 {
  2968.                     pPrinterPB->writePipeRef = pPrinterPB->pb.usbReference;             // remember the ref
  2969.                     pPrinterPB->out = pPrinterPB->pb;                                    // copy the paramblock
  2970.                     pPrinterPB->out.usbCompletion =  (USBCompletion) NULL;                // for finalize
  2971.  
  2972.                     if ( pPrinterPB->printerProtocol == kUSBPrinterBidirectionalProtocol )
  2973.                         pPrinterPB->pb.usbRefcon = kFindBulkInPipe;
  2974.                     else
  2975.                         pPrinterPB->pb.usbRefcon = kTaskTimeRequired;
  2976.                 }
  2977.                 else
  2978.                 {
  2979.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindBulkOutPipe failed", 0);
  2980.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2981.                 }
  2982.                 break;
  2983.                 
  2984.             case kFindBulkInPipe:
  2985.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkInPipe completed", pPrinterPB->pb.usbReference);
  2986.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2987.                 {
  2988.                     pPrinterPB->readPipeRef = pPrinterPB->pb.usbReference;
  2989.                     pPrinterPB->in = pPrinterPB->pb;                                    // copy the paramblock
  2990.                     pPrinterPB->in.usbCompletion =  (USBCompletion) NULL;                // for finalize
  2991.  
  2992.                     pPrinterPB->pb.usbRefcon = kTaskTimeRequired;
  2993.                 }
  2994.                 else
  2995.                 {
  2996.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindBulkInPipe failed", 0);
  2997.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2998.                 }
  2999.                 break;
  3000.                 
  3001.             case kTaskTimeRequired:
  3002.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired completed (now at task time)", pPrinterPB->pb.usbReference);
  3003.             //
  3004.             //    once we know what device we're dealing with
  3005.             //        open the i/o channel(s) to the device
  3006.             //        and enter it in the name registry
  3007.             //
  3008.                 
  3009.                 err = InstallDrivers( pPrinterPB );
  3010.                 if ( err == noErr )
  3011.                 {
  3012.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired - drivers installed", pPrinterPB->pb.usbReference);
  3013.                     err = RegisterDevice( pPrinterPB );
  3014.                     if ( err == noErr )
  3015.                     {
  3016.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired - RegisterDevice successful", pPrinterPB->pb.usbReference);
  3017.                     }
  3018.                     else
  3019.                     {
  3020.                         USBExpertFatalError(pPrinterPB->interfaceRef, err, kPStrPrinterDriverName"kTaskTimeRequired - RegisterDevice failed", 0);
  3021.                     }
  3022.                 }
  3023.                 else
  3024.                 {
  3025.                     USBExpertFatalError(pPrinterPB->interfaceRef, err, kPStrPrinterDriverName"kTaskTimeRequired - InstallDrivers failed", 0);
  3026.                 }
  3027.     
  3028.                 pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;                    // Finalize
  3029.                 if ( pPrinterPB->pb.usbStatus == noErr )
  3030.                 {
  3031.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, "\pPrinter driver now exiting setup, calling suspend", pPrinterPB->interfaceRef );
  3032.                     USBPrintDoSuspendResume(pPrinterPB->interfaceRef); 
  3033.                     pPrinterPB->pb.usbRefcon = kReturnFromDriver;
  3034.                     pPrinterPB->printerConfigured = true;
  3035.                 }
  3036.                 else
  3037.                 {
  3038.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"RegisterDevice failed", 0);
  3039.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3040.                 }
  3041.                 break;
  3042.                 
  3043.             case kGetCentronicsStatus:
  3044.                 //
  3045.                 //    if InitiateTransaction fell through on it's kTaskTimeRequired case we'll end up here
  3046.                 //
  3047.                 if ( pPrinterPB->pb.usbStatus == noErr )
  3048.                 {
  3049.                     unsigned char text[255];
  3050.                     sprintf( (char *)text, " Centronics Status: 0x%02x", pPrinterPB->centronics.b );
  3051.                     text[0] = CStrLen((char *)text); // c2pstr
  3052.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, text, pb->usbStatus );
  3053.                     
  3054. #if DEBUG
  3055.                     if ( !pPrinterPB->centronics.status.notError )
  3056.                     {
  3057.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"Error at printer", pPrinterPB->pb.usbStatus);
  3058.                     }
  3059.                     if ( pPrinterPB->centronics.status.paperError )
  3060.                     {
  3061.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"Check paper", pPrinterPB->pb.usbStatus);
  3062.                     }
  3063.                     if ( !pPrinterPB->centronics.status.select )
  3064.                     {
  3065.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"printer offline", pPrinterPB->pb.usbStatus);
  3066.                     }
  3067. #endif
  3068.                     pPrinterPB->pb.usbRefcon = kDelayGetCentronicsStatus;
  3069.                 }
  3070.                 else
  3071.                 {
  3072.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCentronicsStatus - error getting centronics status", pPrinterPB->pb.usbStatus);
  3073.                 }
  3074.                 break;
  3075.                 
  3076.             case kDelayGetCentronicsStatus:
  3077.                 //
  3078.                 //    loop around continually getting status
  3079.                 //
  3080.                 if ( pPrinterPB->pb.usbStatus == noErr )
  3081.                 {
  3082.                     pPrinterPB->pb.usbRefcon = kGetCentronicsStatus;
  3083.                 }
  3084.                 break;
  3085.             case kNilCompletion:
  3086.             default:
  3087.                 if ( pPrinterPB->pb.usbStatus == noErr )
  3088.                     pPrinterPB->pb.usbRefcon = kUndefined | kReturnFromDriver;
  3089.                 break;
  3090.         }
  3091.     }
  3092.     
  3093.     // did the removal notification get called?  If so, don't start another transaction.  Just exit
  3094.    if (!pPrinterPB->terminating)
  3095.     {
  3096.         if (pPrinterPB->pb.usbStatus == noErr )
  3097.         {
  3098.             if (!(pPrinterPB->pb.usbRefcon & kReturnFromDriver))
  3099.                 PrinterDeviceInitiateTransaction(pb);
  3100.         }
  3101.         else if ( pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  3102.         {
  3103.             USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, StateStr(pPrinterPB->pb.usbRefcon, kPString), pPrinterPB->pb.usbRefcon);
  3104.             USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, USBStatusStr(pPrinterPB->pb.usbStatus, kPString), 0);
  3105.         }
  3106.     }
  3107.     else
  3108.     {
  3109.         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3110.     }
  3111.     
  3112.     // If we're exiting the driver, then make certain the completion routine is set to NULL
  3113.     // this lets the driver removal task know that there's nothing pending.
  3114.     if ( pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  3115.     {
  3116.         pPrinterPB->pb.usbCompletion    = (USBCompletion) NULL;
  3117.     }
  3118. }
  3119.  
  3120. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3121.     Name:        PrinterDeviceInitiateTransaction
  3122.  
  3123.     Input Parameters:    
  3124.         pb            USB parameter block
  3125.         
  3126.     Output Parameters:
  3127.         
  3128.     Description:
  3129.         Since USB transactions are asynchronous we use the refCon field
  3130.         in the parameter block to implement the following logic via a state machine.
  3131.  
  3132.         Start out by getting the device configuration descriptor
  3133.         If the device has more than one printing interface
  3134.             If a bidirectional interface exists
  3135.                 select it
  3136.             Else
  3137.                 select the (mandatory) unidirectional interface
  3138.         Get the (mandatory) 1284 capability string
  3139.         Open pipes to the BulkOut (and optional BulkIn) endpoints
  3140.         Install read and write drivers in the unit table
  3141.         Using information from the capability string
  3142.             enter the printer in the MacOS name registry.
  3143.         
  3144.  
  3145.  
  3146.  
  3147.  
  3148.  
  3149.  
  3150. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3151. void
  3152. PrinterDeviceInitiateTransaction(USBPB *pb)
  3153. {
  3154. register struct usbPrinterPBStruct    *pPrinterPB;
  3155. UInt16        length;
  3156. OSStatus    err;
  3157.  
  3158.     pPrinterPB = (struct usbPrinterPBStruct *)(pb);
  3159.     
  3160.     pPrinterPB->transDepth++;
  3161.     if ((pPrinterPB->transDepth < 0) || (pPrinterPB->transDepth > 1))
  3162.     {
  3163.         USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName"InitiateTransaction illegal transaction depth", 0);
  3164.     }
  3165.     IF_DEBUG( USBExpertStatusLevel(5 pPrinterPB->deviceRef, StateStr(pPrinterPB->pb.usbRefcon, kPString), 0) );     
  3166.     
  3167.     pPrinterPB->delayInProgress = false;
  3168.     switch(pPrinterPB->pb.usbRefcon & ~kRetryTransaction)
  3169.     {
  3170.         case kFindInterface_bidirectional:
  3171.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_bidirectional", 0);
  3172.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3173.             
  3174.             pPrinterPB->pb.usbBuffer = 0;
  3175.             pPrinterPB->pb.usbActCount = 0;
  3176.             pPrinterPB->pb.usbReqCount = 0;
  3177.             pPrinterPB->pb.usb.cntl.WIndex = 0;
  3178.             pPrinterPB->pb.usb.cntl.WValue = 0;
  3179.             pPrinterPB->pb.usbClassType = kUSBPrintingClass;
  3180.             pPrinterPB->pb.usbSubclass = kUSBPrinterSubclass;
  3181.             pPrinterPB->pb.usbProtocol = kUSBPrinterBidirectionalProtocol;
  3182.             
  3183.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3184.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3185.             err = USBFindNextInterface(pb);
  3186.             if(immediateError(err))
  3187.             {
  3188.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kFindInterface_bidirectional - immediate error", err);
  3189.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3190.             }
  3191.             break;
  3192.     
  3193.         case kFindInterface_unidirectional:
  3194.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_unidirectional", 0);
  3195.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3196.             
  3197.             pPrinterPB->pb.usbBuffer = 0;
  3198.             pPrinterPB->pb.usbActCount = 0;
  3199.             pPrinterPB->pb.usbReqCount = 0;
  3200.             pPrinterPB->pb.usb.cntl.WIndex = 0;
  3201.             pPrinterPB->pb.usb.cntl.WValue = 0;
  3202.             pPrinterPB->pb.usbClassType = kUSBPrintingClass;
  3203.             pPrinterPB->pb.usbSubclass = kUSBPrinterSubclass;
  3204.             pPrinterPB->pb.usbProtocol = kUSBPrinterUnidirectionalProtocol;
  3205.             
  3206.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3207.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3208.             err = USBFindNextInterface(pb);
  3209.             if(immediateError(err))
  3210.             {
  3211.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kFindInterface_unidirectional - immediate error", err);
  3212.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3213.             }
  3214.             break;
  3215.     
  3216.         case kOpenDevice:
  3217.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kOpenDevice", 0);
  3218.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3219.             
  3220.             pPrinterPB->pb.usbBuffer = 0;
  3221.             pPrinterPB->pb.usbActCount = 0;
  3222.             pPrinterPB->pb.usbReqCount = 0;
  3223.             pPrinterPB->pb.usb.cntl.WValue = pPrinterPB->configurationNumber;
  3224.             
  3225.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3226.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3227.             err = USBOpenDevice(pb);
  3228.             if(immediateError(err))
  3229.             {
  3230.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBOpenDevice - immediate error", err);
  3231.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3232.             }
  3233.             break;
  3234.             
  3235.         case kNewInterfaceRef:
  3236.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kNewInterfaceRef for interface number", pPrinterPB->interfaceNumber);
  3237.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3238.             
  3239.             pPrinterPB->pb.usbBuffer = 0;
  3240.             pPrinterPB->pb.usbActCount = 0;
  3241.             pPrinterPB->pb.usbReqCount = 0;
  3242.             pPrinterPB->pb.usb.cntl.WIndex = pPrinterPB->interfaceNumber;
  3243.             
  3244.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3245.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3246.             err = USBNewInterfaceRef(pb);
  3247.             if(immediateError(err))
  3248.             {
  3249.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBNewInterfaceRef - immediate error", err);
  3250.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3251.             }
  3252.             break;
  3253.             
  3254.  
  3255.         case kSetInterface:
  3256.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kSetInterface to alternate setting", pPrinterPB->alternateSetting);
  3257.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3258.             
  3259.             pPrinterPB->pb.usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBStandard, kUSBInterface);
  3260.         
  3261.             pPrinterPB->pb.usb.cntl.BRequest = kUSBRqSetInterface;
  3262.             pPrinterPB->pb.usb.cntl.WValue = pPrinterPB->alternateSetting;        // alternate setting
  3263.             pPrinterPB->pb.usb.cntl.WIndex = pPrinterPB->interfaceNumber;        // interface
  3264.         
  3265.             pPrinterPB->pb.usbReqCount = 0;
  3266.             pPrinterPB->pb.usbBuffer = NULL;
  3267.         
  3268.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3269.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3270.             err = USBDeviceRequest(pb);
  3271.             if(immediateError(err))
  3272.             {
  3273.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kSetInterface - immediate error", err);
  3274.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3275.             }
  3276.             break;
  3277.  
  3278.  
  3279.         case kConfigureInterface:
  3280.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kConfigureInterface for alternate setting", pPrinterPB->alternateSetting);
  3281.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3282.             
  3283.             pPrinterPB->pb.usbBuffer = 0;
  3284.             pPrinterPB->pb.usbActCount = 0;
  3285.             pPrinterPB->pb.usbReqCount = 0;
  3286.             pPrinterPB->pb.usbOther = pPrinterPB->alternateSetting;
  3287.             
  3288.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3289.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3290.             err = USBConfigureInterface(pb);
  3291.             if(immediateError(err))
  3292.             {
  3293.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBConfigureInterface - immediate error)", err);
  3294.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3295.             }
  3296.             break;
  3297.             
  3298.         case kGetCapabilityString:
  3299.             //
  3300.             //    once the interface (and alternate) is assinged
  3301.             //        we can retreive the 1284 capability string to see what kind of printer
  3302.             //        is attached
  3303.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCapabilityString", 0);
  3304.             pPrinterPB->pCapabilityString = pPrinterPB->capability;
  3305.             
  3306.             GetCapability( pPrinterPB, pPrinterPB->pCapabilityString, sizeof(pPrinterPB->capability) );
  3307.             break;
  3308.             
  3309.         case kDelayGetCapability:
  3310.             //
  3311.             //    USS-720 USB-parallel cable: couldn't get the capability string because the printer is off
  3312.             //        Delay a few seconds and try again.
  3313.             //        Will succeed when the user turns the printer on.
  3314.             //
  3315.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kDelayGetCapability", 0);
  3316.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3317.             
  3318.             pPrinterPB->pb.usbBuffer = 0;
  3319.             pPrinterPB->pb.usbActCount = 0;
  3320.             pPrinterPB->pb.usbReqCount = kUSS720MillisecondDelay;
  3321.             pPrinterPB->pb.usbFlags = kUSBTaskTimeFlag;
  3322.             
  3323.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3324.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3325.             pPrinterPB->delayInProgress = true;
  3326.             err = USBDelay(&pPrinterPB->pb);
  3327.             if(immediateError(err))
  3328.             {
  3329.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kDelayGetCapability - immediate error", 0);
  3330.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3331.             }
  3332.             break;
  3333.             
  3334.         case kAllocateCapabilityMem:
  3335.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kAllocateCapabilityMem", 0);
  3336.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3337.             length = *(UInt16*)(pPrinterPB->capability);
  3338.             pPrinterPB->pb.usbBuffer = 0;
  3339.             pPrinterPB->pb.usbActCount = 0;
  3340.             pPrinterPB->pb.usbReqCount = length;
  3341.             pPrinterPB->pb.usbFlags = 0;
  3342.             
  3343.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3344.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3345.             err = USBAllocMem(&pPrinterPB->pb);
  3346.             if(immediateError(err))
  3347.             {
  3348.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kAllocateCapabilityMem - immediate error", 0);
  3349.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3350.             }
  3351.             break;
  3352.         
  3353.         case kGetFullCapabilityString:
  3354.             //
  3355.             // the capability string was too long to fit in the statically allocated space
  3356.             // need to release this memory when we finalize our driver
  3357.             //
  3358.  
  3359.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetFullCapabilityString", 0);
  3360.             length = *(UInt16*)(pPrinterPB->capability);
  3361.             if ( pPrinterPB->pCapabilityString )
  3362.                 GetCapability( pPrinterPB, pPrinterPB->pCapabilityString, length );
  3363.             else
  3364.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"Can't allocate capability memory", 0);
  3365.             break;
  3366.             
  3367.         case kGetInterface:
  3368.             // failsafe check that we've got the right setup
  3369.             //    it's possible the device didn't respond to our SetInterface
  3370.             GetInterface( &pPrinterPB->pb, &pPrinterPB->whichAltInterface );
  3371.             break;
  3372.  
  3373.         case kFindBulkOutPipe:
  3374.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkOutPipe", 0);
  3375.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3376.             
  3377.             pPrinterPB->pb.usbBuffer = 0;
  3378.             pPrinterPB->pb.usbActCount = 0;
  3379.             pPrinterPB->pb.usbReqCount = 0;
  3380.             pPrinterPB->pb.usbFlags = kUSBOut;
  3381.             pPrinterPB->pb.usbClassType = kUSBBulk;
  3382.             
  3383.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3384.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3385.             err = USBFindNextPipe( &pPrinterPB->pb );
  3386.             if (immediateError(err))
  3387.             {
  3388.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"kFindBulkOutPipe - immediate error", err);
  3389.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3390.             }
  3391.             break;
  3392.             
  3393.         case kFindBulkInPipe:    
  3394.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkInPipe", 0);
  3395.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3396.             
  3397.             pPrinterPB->pb.usbBuffer = 0;
  3398.             pPrinterPB->pb.usbActCount = 0;
  3399.             pPrinterPB->pb.usbReqCount = 0;
  3400.             pPrinterPB->pb.usbFlags = kUSBIn;
  3401.             pPrinterPB->pb.usbClassType = kUSBBulk;
  3402.             
  3403.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3404.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3405.             err = USBFindNextPipe( &pPrinterPB->pb );
  3406.             if (immediateError(err))
  3407.             {
  3408.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"kFindBulkInPipe - immediate error", err);
  3409.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3410.             }
  3411.             break;
  3412.             
  3413.         case kTaskTimeRequired:
  3414.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired", 0);
  3415.              // to stress test usb bus, fallthrough to kGetCentronicsStatus 
  3416.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3417.             
  3418.             pPrinterPB->pb.usbBuffer = 0;
  3419.             pPrinterPB->pb.usbActCount = 0;
  3420.             pPrinterPB->pb.usbReqCount = kUSBNoDelay;
  3421.             pPrinterPB->pb.usbFlags = kUSBTaskTimeFlag;
  3422.             
  3423.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3424.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3425.             pPrinterPB->delayInProgress = true;
  3426.             err = USBDelay(&pPrinterPB->pb);
  3427.             if(immediateError(err))
  3428.             {
  3429.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kTaskTimeRequired - immediate error", 0);
  3430.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3431.             }
  3432.             break;
  3433.  
  3434.         case kGetCentronicsStatus:
  3435.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3436.  
  3437.             CentronicsStatus( &pPrinterPB->pb,  &pPrinterPB->centronics.b, pPrinterPB->interfaceNumber );
  3438.             
  3439.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3440.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3441.             err = USBDeviceRequest(&pPrinterPB->pb);
  3442.             if(immediateError(err))
  3443.             {
  3444.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kGetCentronicsStatus Immediate error", 0);
  3445.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3446.             }
  3447.             break;
  3448.             
  3449.         case kDelayGetCentronicsStatus:
  3450.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3451.  
  3452.             pPrinterPB->pb.usbBuffer = 0;
  3453.             pPrinterPB->pb.usbActCount = 0;
  3454.             pPrinterPB->pb.usbReqCount = kUSS720StatusMSDelay;
  3455.             
  3456.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3457.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3458.             pPrinterPB->delayInProgress = true;
  3459.             err = USBDelay(&pPrinterPB->pb);
  3460.             if(immediateError(err))
  3461.             {
  3462.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kDelayGetCentronicsStatus - immediate error", 0);
  3463.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3464.             }
  3465.             break;
  3466.             
  3467.         default:
  3468.             USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName"InitiateTransaction - unknown state", pPrinterPB->pb.usbRefcon);
  3469.             pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3470.             break;
  3471.     }
  3472.     
  3473.     if (pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  3474.     {
  3475.         pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;
  3476.         pPrinterPB->pb.usbRefcon &= ~kTransactionPending;
  3477.     }
  3478. }
  3479.  
  3480.  
  3481. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3482.     Name:        PrintDriverEntry
  3483.  
  3484.     Input Parameters:    
  3485.         
  3486.     Output Parameters:
  3487.         
  3488.     Description:
  3489.         This is where the system instantiates a USB printing device.
  3490.  
  3491.         We need to install drivers in the MacOS unitTable, and a reference
  3492.         in the name registry.
  3493.         
  3494.         But the information we need to do this is only available after some 
  3495.         USB transactions have completed. So we initiate here a series of asynchronous
  3496.         USB operations to get that information (by calling the first 
  3497.  
  3498.  
  3499.  
  3500.  
  3501.  
  3502. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3503. void 
  3504. PrintDriverEntry(
  3505.     USBDeviceRef                    deviceRef,
  3506.     USBDeviceDescriptorPtr            pDeviceDesc,
  3507.     USBInterfaceDescriptorPtr        pInterfaceDesc,
  3508.     UInt32                            interfaceNumber
  3509.     )
  3510. {
  3511.     static Boolean        beenThereDoneThat = false;
  3512.     OSStatus                err;
  3513.     
  3514.     
  3515.     RoutineDescriptor qw = BUILD_ROUTINE_DESCRIPTOR( uppQueueUSBWriteProcInfo, QueueWrite);
  3516.     RoutineDescriptor qr = BUILD_ROUTINE_DESCRIPTOR( uppQueueUSBReadProcInfo, QueueRead);
  3517.     RoutineDescriptor qa = BUILD_ROUTINE_DESCRIPTOR( uppAbortProcInfo, Abort);
  3518.     RoutineDescriptor qs = BUILD_ROUTINE_DESCRIPTOR( uppControlStatusProcInfo, ControlStatusRequests );
  3519.     
  3520.     if( !beenThereDoneThat)
  3521.     {
  3522.         printerClassRecord.terminating = false;
  3523.         printerClassRecord.printerRegistered = false;
  3524.         beenThereDoneThat = true;
  3525.         
  3526.         //DebugStr("\pIn Printer Driver Entry");
  3527.         USBExpertStatusLevel(kNormalStatusLevel, deviceRef, kPStrPrinterDriverName"Starting USB Printer Driver", 0);
  3528.         
  3529.         printerClassRecord.deviceDescriptor = *pDeviceDesc;    /* keep a copy of the device descriptor */
  3530.         printerClassRecord.pInterfaceDescriptor = pInterfaceDesc;
  3531.         printerClassRecord.interfaceNumber = interfaceNumber;
  3532.         
  3533.         printerClassRecord.deviceRef = deviceRef;
  3534.         printerClassRecord.interfaceRef = deviceRef;
  3535.         
  3536.         printerClassRecord.transDepth = 0;            /* init Delay Callback Depth */
  3537.     
  3538.         printerClassRecord.inRefNum =  -1;            /* initially no DRVRs added to UnitTable */
  3539.         printerClassRecord.outRefNum =  -1;    
  3540.         err = LoadResources( &printerClassRecord );
  3541.         if ( err != noErr )  
  3542.             USBExpertFatalError( deviceRef, err, kPStrPrinterDriverName"LoadResources failed", 0);
  3543.         //
  3544.         //    routines to write and read to the device must be called by 68K DRVR
  3545.         //        so we use mixed-mode manager to dispatch between PPC and 68K
  3546.         //
  3547.         printerClassRecord.qwrite = (QueueUSBWriteUPP) &printerClassRecord.qwriteRD;
  3548.         printerClassRecord.qwriteRD = qw;
  3549.     
  3550.         printerClassRecord.qread = (QueueUSBReadUPP) &printerClassRecord.qreadRD;
  3551.         printerClassRecord.qreadRD = qr;    
  3552.         
  3553.         printerClassRecord.qstatus = (ControlStatusUPP) &printerClassRecord.qstatusRD;
  3554.         printerClassRecord.qstatusRD = qs;
  3555.  
  3556.         printerClassRecord.qabort = (AbortUPP) &printerClassRecord.qabortRD;
  3557.         printerClassRecord.qabortRD = qa;
  3558.  
  3559.         printerClassRecord.r = (QueueUSBReadUPP) QueueRead;
  3560.         printerClassRecord.w = (QueueUSBWriteUPP) QueueWrite;
  3561.         printerClassRecord.s = (ControlStatusUPP) ControlStatusRequests;
  3562.         printerClassRecord.a = (AbortUPP) Abort;
  3563.    
  3564.         SetNullUSBParamBlock( deviceRef, &printerClassRecord.pb );
  3565.         SetNullUSBParamBlock( 0, &printerClassRecord.in );        // fill in pipe ref later
  3566.         SetNullUSBParamBlock( 0, &printerClassRecord.out );    // fill in pipe ref later
  3567.         
  3568.         CStrCopy((char *)printerClassRecord.name, "");
  3569.         CStrCopy((char *)printerClassRecord.model, "");
  3570.  
  3571. #if DOUBLE_BUFFER
  3572.         //
  3573.         // Assume 1. TRANSFER_SIZE is a power of 2
  3574.         //    Assume 2. malignedBuffer is allocated to be 3*TRANSFER_SIZE
  3575.         //
  3576.         printerClassRecord.pageWriteAlignedBufferSize = TRANSFER_SIZE;                            // should get this from VM
  3577.         printerClassRecord.pageWriteAlignedBuffer = printerClassRecord.malignedBuffer;
  3578.  
  3579.         // align it below the buffer, then bring it into the range of the buffer
  3580.         *((UInt32 *) &printerClassRecord.pageWriteAlignedBuffer) &= ~(printerClassRecord.pageWriteAlignedBufferSize - 1);    //assumption1
  3581.         *((UInt32 *) &printerClassRecord.pageWriteAlignedBuffer) += printerClassRecord.pageWriteAlignedBufferSize;            //assumption2
  3582.  
  3583.         printerClassRecord.pageReadAlignedBufferSize = TRANSFER_SIZE;
  3584.         printerClassRecord.pageReadAlignedBuffer = printerClassRecord.pageWriteAlignedBuffer + TRANSFER_SIZE;
  3585.         
  3586. #endif
  3587.         printerClassRecord.printerConfigured = false;
  3588.     
  3589.         //
  3590.         //    Just to be thorough, lets hold our paramter blocks so that we won't page them at
  3591.         //        interrupt time. (We should be in the System heap and automatically held.)
  3592.         //
  3593.         HoldMemory( &printerClassRecord, sizeof(struct usbPrinterPBStruct) );
  3594.  
  3595.         CheckUSBVersion();
  3596.         
  3597.         //
  3598.         // Start out at first state
  3599.         //
  3600.         printerClassRecord.pCapabilityString = printerClassRecord.capability;
  3601.         printerClassRecord.pb.usbRefcon = kFindInterface_bidirectional;
  3602.         
  3603.         // don't start if we received a removal notification just as we're starting up
  3604.         if (printerClassRecord.terminating)
  3605.         {
  3606.             printerClassRecord.pb.usbCompletion    = (USBCompletion) NULL;
  3607.         }
  3608.         else
  3609.         {
  3610.             PrinterDeviceInitiateTransaction(&printerClassRecord.pb);
  3611.         }
  3612.     }
  3613. }
  3614.  
  3615. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3616.     Name:        PrinterRemovalNotification
  3617.  
  3618.     Input Parameters:    
  3619.         
  3620.     Output Parameters:
  3621.         
  3622.     Description:
  3623.         release any allocated storage
  3624.         remove DRVRs from the UnitTable
  3625.  
  3626.         One small complication happens when the USS-720 cable is used. It's possible
  3627.         that the user has the device plugged in, but the printer wasn't powered on.
  3628.         In this case, our state machine is still cycling between the states 
  3629.         kDelayGetCapability and kGetCapabilityString. If we terminate before the delay
  3630.         returns we'll crash the system. We monitor terminating to handle this
  3631.         
  3632.  
  3633.  
  3634.  
  3635.  
  3636.  
  3637.  
  3638.  
  3639.  
  3640.  
  3641.  
  3642. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3643. OSStatus
  3644. PrinterRemovalNotification( void )
  3645. {
  3646. static    Boolean    logfileclosed = false;
  3647. static    Boolean    aborted = false;
  3648. static    Boolean    deregistered = false;
  3649. static    Boolean    readpipeaborted = false;
  3650. static    Boolean    writepipeaborted = false;
  3651. static    Boolean    timedout = false;
  3652. OSStatus            result = noErr;
  3653. static unsigned long    tc = 0;
  3654.     //
  3655.     //    notify state machine not to continue
  3656.     //
  3657.     printerClassRecord.terminating = true;
  3658.     
  3659.     USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Driver removal notification received", 0);
  3660.     if (!logfileclosed)
  3661.     {
  3662.         USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Closing printer log file", 0);
  3663.         LOGGING( fclose( logfile ) );
  3664.         logfileclosed = true;
  3665.     }
  3666.     
  3667.     // if the printer was never registered, then don't try to deregister it
  3668.     if (!(printerClassRecord.printerRegistered))
  3669.         deregistered = true;
  3670.         
  3671.     if (!deregistered)    
  3672.     {
  3673.         //
  3674.         //    remove printer from the name registry
  3675.         //
  3676.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Removed printer entry from nameregistry", 0);
  3677.         DeregisterDevice( &printerClassRecord );
  3678.         deregistered = true;
  3679.     }
  3680.  
  3681.     // per the Mac OS USB DDK API Ref 
  3682.     // "If the device associated with this call [USBDelay] is unplugged and its driver removed while
  3683.     //  this function call is pending, the function will not complete."
  3684.     // therefore don't hang around if a delay is in progress
  3685.     if (( printerClassRecord.pb.usbCompletion != (USBCompletion) NULL ) && (!printerClassRecord.delayInProgress))
  3686.     {
  3687.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Waiting for configuration to complete", printerClassRecord.pb.usbRefcon);
  3688.         return (OSStatus) kUSBDeviceBusy;
  3689.     }
  3690.     
  3691.     // Abort any outstanding write requests
  3692.     if (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL ) && (!writepipeaborted))
  3693.     {
  3694.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Abort write pipe", printerClassRecord.writePipeRef);
  3695.         USBAbortPipeByReference( printerClassRecord.writePipeRef );
  3696.         writepipeaborted = true;
  3697.         return (OSStatus) kUSBDeviceBusy;
  3698.     }
  3699.     
  3700.     // Abort any outstanding read requests
  3701.     if (( printerClassRecord.in.usbCompletion != (USBCompletion) NULL ) && (!readpipeaborted))
  3702.     {
  3703.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Abort read pipe", printerClassRecord.readPipeRef );
  3704.         USBAbortPipeByReference( printerClassRecord.readPipeRef );
  3705.         readpipeaborted = true;
  3706.         return (OSStatus) kUSBDeviceBusy;
  3707.     }
  3708.     
  3709.     // Abort any outstanding transactions
  3710.     if (!aborted)
  3711.     {
  3712.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Call Abort()", 0);
  3713.         Abort( 0, &printerClassRecord );
  3714.         aborted = true;
  3715.     }
  3716.  
  3717.     // wait up to ten seconds for the read & write routines to complete.  When they do, the completion procptrs will be NULL'd
  3718.     if (tc == 0)
  3719.         tc = TickCount() + 10*60;
  3720.         
  3721.     if ( TickCount() >= tc )
  3722.         timedout = true;
  3723.         
  3724.     if (( TickCount() < tc ) &&
  3725.          (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL) ||
  3726.           ( printerClassRecord.in.usbCompletion != (USBCompletion) NULL )))
  3727.     {
  3728.         return (OSStatus) kUSBDeviceBusy;
  3729.     }
  3730.     
  3731.     // Put the appropriate timeout message in the log
  3732.     if ( timedout )
  3733.     {
  3734.         USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"took longer than 10 seconds for read/write pipes to complete", 0);
  3735.     }
  3736.     else
  3737.     {
  3738.         USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Pipes closed normally", 0);
  3739.     }
  3740.     
  3741.     if (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL) ||
  3742.           ( printerClassRecord.in.usbCompletion != (USBCompletion) NULL ))
  3743.     {
  3744.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Completion procs are not nil!!", 0);
  3745.     }
  3746.     
  3747.     // remove our unit table drivers
  3748.     if (printerClassRecord.outRefNum != -1 )
  3749.     {
  3750.         TradRemoveDriver( printerClassRecord.outRefNum, false );
  3751.         printerClassRecord.outRefNum = -1;
  3752.     }
  3753.     
  3754.     if (printerClassRecord.inRefNum != -1 )
  3755.     {
  3756.         TradRemoveDriver( printerClassRecord.inRefNum, false );
  3757.         printerClassRecord.inRefNum = -1;
  3758.     }
  3759.  
  3760.     //
  3761.     //    release any allocated storage
  3762.     //
  3763.     if ( printerClassRecord.pCapabilityString != printerClassRecord.capability )
  3764.     {
  3765.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Deallocated capability string memory", 0);
  3766.         printerClassRecord.pb.usbReference = printerClassRecord.deviceRef;             
  3767.         printerClassRecord.pb.usbFlags = 0;             
  3768.         printerClassRecord.pb.usbRefcon = kDeallocateCapbilityString;             
  3769.         printerClassRecord.pb.usbBuffer = printerClassRecord.pCapabilityString;        
  3770.         printerClassRecord.pb.usbCompletion = (USBCompletion)kUSBNoCallBack;
  3771.         printerClassRecord.delayInProgress = true;        // this prevents the control pipe completion procptr from being checked
  3772.         USBDeallocMem(&printerClassRecord.pb);
  3773.         
  3774.         printerClassRecord.pCapabilityString = printerClassRecord.capability;
  3775.         return (OSStatus) kUSBDeviceBusy;
  3776.     }
  3777.  
  3778.     //
  3779.     //    don't need to hang on to param blocks after we've gone away
  3780.     //
  3781.     UnholdMemory( &printerClassRecord, sizeof(struct usbPrinterPBStruct) );
  3782.  
  3783.     USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Ready for removal", 0);
  3784.     return kUSBNoErr;
  3785. }
  3786.  
  3787. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3788.     Name:        CFMInitialization
  3789.  
  3790.     Input Parameters:    
  3791.         initBlock
  3792.         
  3793.     Output Parameters:
  3794.         printerClassDriverFileSpec        set global
  3795.         
  3796.     Description:
  3797.         We use the code fragment initialization to get our filespec which 
  3798.         LoadResources will use to open our resource fork.
  3799.         
  3800.         A peculiarity of the USB 1.0 implementation is that does not lock the
  3801.         driver into physical memory. As a result a driver which does not call
  3802.         SetDriverClosureMemory on it's fragment will likely be paged in during
  3803.         interrupt time and a double bus-fault will occur. The solution for this
  3804.         is to have the USB Expert call SetDriverClosureMemory in a future release
  3805.         of the USB stack. In the meantime, we call it on ourselves to lock us into
  3806.         physical memory. When the USB stack is revved, one call to SetDriverClosureMemory
  3807.         (either this one or the Expert's) will be treated as a NOP.
  3808.  
  3809.  
  3810.  
  3811.  
  3812. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3813. OSErr
  3814. CFMInitialization( CFragInitBlock *initBlock )
  3815. {
  3816.     //
  3817.     //    get a reference to our file so that we can open up the resource fork later on
  3818.     //
  3819.     if ( CFragHasFileLocation( initBlock->fragLocator.where ) )
  3820.         printerClassDriverFileSpec = *(initBlock->fragLocator.u.onDisk.fileSpec);
  3821.  
  3822.     return noErr;
  3823.  
  3824. }
  3825.  
  3826. // eof
  3827.